String in reverse order of words

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:

The INPUT: "A Good Example" 
the Output: "A Good Example" 
Explanation: Multiple Spaces by You need to the reduce the BETWEEN TWO words to A SINGLE at The Space in the reversed String. 

The basic idea is, first reverse the entire string, then reverse each word. Handle extra spaces in the process. In-place algorithm
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;
    }
};

  

Guess you like

Origin www.cnblogs.com/vimery/p/11569204.html