【LeetCode】151. Reverse Words in a String

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".

click to show clarification.

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) 
    {
        string rs = "";
        int i = 0;
        while(true)
        {
            // skip leading space
            while(i < s.size() && s[i] == ' ')
                i ++;
            string word = "";
            // s[i] points to first non-space
            while(i < s.size() && s[i] != ' ')
            {
                word += s[i];
                i ++;
            }
            if(word != "")
                rs = word + " " + rs;
            else    // i == s.size()
                break;
        }
        if(rs != "")
            rs.erase(rs.end()-1);   // if rs contains words, erase the last space
        s = rs;
    }
};

posted @ 2014-11-12 11:27  陆草纯  阅读(230)  评论(0编辑  收藏  举报