151. Reverse Words in a String

问题描述:

Given an input string, reverse the string word by word.

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

 

解题思路:

我想的办法使用getline读入字符串并以‘ ’作为分隔符,需要检查当前获取字符串是否为空。

空间复杂度不为O(1),所以我就折叠一下:)

来看看空间复杂度为1的解法(来自于Grandyang):

使用reverse()翻转字符串,然后再单独翻转单词。

使用了辅助变量StoreIndex来记录新的字符串中单词的开始

初始值为0。

找到第一个不为空的字符后,将其拷贝到storeIndex的位置,然后用reverse再翻转单词。

为了防止出现“    ”开始的情况,用了resize。

 

代码:

class Solution {
public:
    void reverseWords(string &s) {
        vector<string> v;
        stringstream ss(s);
        string temp;
        while(getline(ss, temp, ' ')){
            if(temp.size() != 0)
                v.push_back(temp);
        }
        s.clear();
        for(int i = v.size() - 1; i > -1; i--){
            s += v[i] + " ";
        }
        s = s.substr(0, s.size() - 1);
    }
};
空间复杂度不为O(1)

 

空间复杂度为O(1) :

class Solution {
public:
    void reverseWords(string &s) {
        int storeIdx = 0, n = s.size();
        reverse(s.begin(), s.end());
        for(int i = 0; i < n; i++ ){
            if(s[i] != ' '){
                if(storeIdx != 0)
                    s[storeIdx++] = ' ';
                int j = i;
                while(j < n && s[j] != ' ')
                    s[storeIdx++] = s[j++];
                reverse(s.begin()+storeIdx - (j-i), s.begin() + storeIdx);
                i = j;
            }
        }
        s.resize(storeIdx);
    }
};

 

posted @ 2018-06-15 13:53  妖域大都督  阅读(119)  评论(0编辑  收藏  举报