题目:
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)如果是Java,应该跟面试官指出String是immutable,所以需要用char array来做。
2)follow-up问题:k-step reverse。也就是在第二部翻转的时候,把k个单词看作一个长单词,进行翻转。
public void reverseWords(char []s){
// 将整个char数组翻转
reverseMethod(s, 0, s.length);
// 再将每个单词翻转 如果遇到"" 或 j = s.length,单
for(int i = 0, j = 0; j <=s.length; j++){
if(j == s.length || s[j] == ' '){
reverseMethod(s, i , j);
i = j + 1;
}
}
}
// 倒转方法
private void reverseMethod(char []s , int start , int end){
for(int i = 0; i < (start + end) / 2; i++){
char temp = s[end + i];
s[end + i] = s[start + i];
s[start + i] = temp;
}
}