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?
1、刚开始的想法是找到第一个和最后一个单词,然后交换他们两个,但是遇到的问题是两个单词长度不一致的时候会很麻烦,就需要将剩余的字符串整个进行移动,麻烦,且效率很低。
2、参考了discuss,发现很其实想法很简单,就是分两步:第一步就是把整个字符串倒过来,第二步就是再翻回来之后再把每个单词反转一次就好了。
public class Solution {
public void reverseWords(char[] s) {
int len = s.length;
reverse(s, 0, len - 1);
int start = 0;
for (int i = 0; i < len - 1; i++){
if (s[i] == ' '){
reverse(s, start, i - 1);
start = i + 1;
}
}
reverse(s, start, len - 1);
}
private void reverse(char[] s, int start, int end){
while (start < end){
char ch = s[start];
s[start] = s[end];
s[end] = ch;
start++;
end--;
}
}
}