题目:

    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个单词看作一个长单词,进行翻转。

    1. public void reverseWords(char []s){
    2. // 将整个char数组翻转
    3. reverseMethod(s, 0, s.length);
    4. // 再将每个单词翻转 如果遇到"" 或 j = s.length,单
    5. for(int i = 0, j = 0; j <=s.length; j++){
    6. if(j == s.length || s[j] == ' '){
    7. reverseMethod(s, i , j);
    8. i = j + 1;
    9. }
    10. }
    11. }
    12. // 倒转方法
    13. private void reverseMethod(char []s , int start , int end){
    14. for(int i = 0; i < (start + end) / 2; i++){
    15. char temp = s[end + i];
    16. s[end + i] = s[start + i];
    17. s[start + i] = temp;
    18. }
    19. }