leetcode 151. https://leetcode.com/problems/reverse-words-in-a-string/

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

基本思想为,先逆序整个字符串,然后逆序每个单词。在这个过程中处理多余的空格。In-place算法
class Solution {
public:
    string reverseWords(string s) {
        // reverse whole string
        reverse(s.begin(), s.end());
        // reverse each word
        int i = 0,j = 0, storedIndex = 0;
        while (i < s.size()){
            // put i to the first letter of a word
            while (i < s.size() && s[i] == ' ') ++i;
            // add a space if this is not the first and last word
            if (i < s.size() && storedIndex != 0) s[storedIndex++] = ' ';
            j = i;
            // put j to the end of the word
            while (j < s.size() && s[j] != ' ') ++j;
            // reverse this word. There may be spaces in front of the word, and after reverse it goes to the end.
            // if s contains only space, i == j, reverse will do nothing
            reverse(s.begin()+storedIndex, s.begin()+j);
            // put stored index to the end of the word
            storedIndex += j - i;
            // put i to the start of next search
            i = j;
        }
        // finally, storedIndex will point to the letter next to the last word
        s.erase(s.begin()+storedIndex, s.end());
        return s;
    }
};

  

01-19 12:32