Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Could you do it in-place without allocating extra space?
思路:就是先整体reverse,然后再每个局部reverse,记得最后while跳出来之后,最后一个单词也要reverse一下;
public class Solution {
public void reverseWords(char[] s) {
if(s == null || s.length == 0) return;
reverse(s, 0, s.length-1);
int i=0; int j=0;
while(j<s.length){
while(j<s.length && s[j] != ' '){
j++;
}
if(j>=s.length) break;
reverse(s, i, j-1);
i=j+1;
j++;
}
reverse(s, i, j-1);
}
public void reverse(char[] s, int i, int j) {
while(i<j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}