Reverse Words in a String II

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? 也就是不能用I 那样存个暂存word string来翻转

分析抄达达“http://www.danielbit.com/blog/puzzle/leetcode/leetcode-reverse-words-in-a-string-ii

[分析]
该题在LeetCode中假设开头和结尾没有空格,而且单词之间只有一个空格。但其实不需要这些假设也是可以的,就是代码会比较复杂。
思路就是两步走,第一步就是将整个字符串翻转。然后从头逐步扫描,将每个遇到单词再翻转过来。

[注意事项]
1)如果是Java,应该跟面试官指出String是immutable,所以需要用char array来做。

2)follow-up问题:k-step reverse。也就是在第二部翻转的时候,把k个单词看作一个长单词,进行翻转。

code 我觉得这个写的清楚 ref

http://www.cnblogs.com/EdwardLiu/p/4306561.html

public class Solution {

    public void reverseWords(char[] s) {

        if (s.length == 0) return;

        reverse(s, 0, s.length-1);

        int last = 0;

        for (int i=0; i<s.length; i++) {

            if (s[i] == ' ') {

                reverse(s, last, i-1);

                last = i + 1;

            }

        }

    }

    

    public void reverse(char[] s, int l, int r) {

        while (l <= r) {

            int temp = s[l];

            s[l] = s[r];

            s[r] = temp;

            l++;

            r--;

        }

    }

}

 

你可能感兴趣的:(String)