Leetcode探索——字节跳动·挑战字符串:翻转字符串里的单词

给定一个字符串,逐个翻转字符串中的每个单词。

示例:  

输入: "the sky is blue",
输出: "blue is sky the".

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。

算法思路:用char res[]保存char str[]从后往前寻找单词,截断单词后存入res[]中;这里用了递归dg(char str[], int tail, char res[], int left),tail为当前遍历到str[]的尾部下标,left为当前res[]存储单词后尾部的下标。注意处理每个单词加空格问题以及最后一个单词的加空格问题。

代码:

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         if(s == null || "".equals(s)) {
 4             return "";
 5         }
 6         char str[] = s.toCharArray();
 7         char res[] = new char[str.length];
 8         int len = dg(str, str.length - 1, res, 0);
 9         return new String(res, 0, len);
10     }
11     
12     public int dg(char str[], int tail, char res[], int left) {
13         while(tail >=0 && str[tail] == ' ') {
14             tail--;
15         }
16         int tright = tail;
17         while(tail >= 0 && str[tail] != ' ') {
18             tail --;
19         }
20         int tleft = tail;
21         if(tright == tleft) {
22             return left;
23         }
24         if(left != 0) {
25             res[left++] = ' ';
26         }
27         for(int j = tleft + 1; j <= tright; j++,left++) {
28             res[left] = str[j];
29         }
30         return dg(str, tail, res, left);
31     }
32 }

 

posted @ 2018-12-26 14:58  trashbird_fly  阅读(49)  评论(0)    收藏  举报