Wednesday, September 17, 2014

[Leetcode] 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:

    vector< string > splitWords(string& str)
    {
        vector< string > strs;
        int i =0;
        while(i < str.size())
        {
            while(i < str.size() && str[i] == ' ')
                i++;
                
            int j = i;
            while(i < str.size() && str[i] != ' ')
                i++;
                
            if (j < str.size())
                strs.push_back(str.substr(j, i-j));
        }
        
        return strs;
    }

    void reverseWords(string &s) {
         vector< string > strs = splitWords(s);
         s.clear();
         for(int i=strs.size()-1; i>=0;i--)
        {
            s.append(strs[i]);
            if (i != 0)
                s.append(" ");
        }
    }
};

No comments:

Post a Comment