Sunday, February 1, 2015

151 Reverse Words in a String

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
class Solution {
public:
    void reverseWords(string &s) {
        stack<string> stk;
        int start=0;
        int end = start;
        while (end<s.size())
        {
            while(start<s.size() && s[start]==' ')
                start++;
            if (start>=s.size())
                break;
            end = start;
            while(end<s.size() && s[end]!=' ')
            {
                end++;
            }
            string tmp = s.substr(start,end-start);
            stk.push(tmp);
            start=end;
        }
        s="";
        while(!stk.empty())
        {
            s+=stk.top()+' ';
            stk.pop();
        }
        if (s.size()>1)
            s.pop_back();
    }
};

No comments:

Post a Comment