Tuesday, February 3, 2015

Day 101, ##, Reverse Words in a String II

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?
------------------------------------------------------
class Solution {
public:
    void reverseWords(string &s) {
        reverse(s.begin(),s.end());
        int i = 0;
        while (i < s.length()) {
            int start = i;
            while (i < s.length() && s[i] != ' ') {
                i++;
            }
            
            reverse(s.begin() + start, s.begin() + i);
            i++;
        }
    }
};

No comments:

Post a Comment