186. Reverse Words in a String II

和rotate array是一个方法,把整个转过来,然后每个词单独转过来

 1     public void reverseWords(char[] s) {
 2         if(s.length == 0) {
 3             return;
 4         }
 5         int len = s.length;
 6         reverse(s, 0, len - 1);
 7         int walker = findNextWord(s, 0);
 8         int runner = findEndOfWord(s, walker);
 9         while(runner <= len) {
10             reverse(s, walker, runner - 1);
11             walker = findNextWord(s, runner);
12             if(walker >= len) {
13                 return;
14             }
15             runner = findEndOfWord(s, walker);
16         }
17     }
18     
19     private int findNextWord(char[] s, int start) {
20         int index = start;
21         while(index < s.length && s[index] == ' ') {
22             index++;
23         }
24         return index;
25     }
26     
27     private int findEndOfWord(char[] s, int start) {
28         int index = start;
29         while(index < s.length && s[index] != ' ') {
30             index++;
31         }
32         return index;
33     }
34     
35     private void reverse(char[] s, int start, int end) {
36         while(end > start) {
37             char x = s[start];
38             s[start] = s[end];
39             s[end] = x;
40             start++;
41             end--;
42         }
43     }

 

posted @ 2016-07-10 06:37  warmland  阅读(139)  评论(0编辑  收藏  举报