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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

思路:先去掉前面多余的空格,然后去掉中间多余的空格用快慢指针实现,然后反转。

class Solution {
public:
    void reverseWords(string &s) {
        int n = s.size();
        int i = 0, j = 0;
        while (j < n) {
            while (j < n && s[j] == ' ') j++;             // 跳过前面空格
            while (j < n && s[j] != ' ') s[i++] = s[j++]; // 保留字母
            while (j < n && s[j] == ' ') j++;             // 跳过中间空格
            if (j < n) s[i++] = ' ';                      // 添加中间的一个空格
        }
        s = s.substr(0, i);
        reverse(s.begin(), s.end());
        int b = 0;
        cout << s << endl;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == ' ') {
                reverse(s.begin() + b, s.begin() + i);
                b = i+1;
            }
        }
        reverse(s.begin()+b, s.end());
    }
};
posted on 2018-02-28 14:49  Beserious  阅读(83)  评论(0编辑  收藏  举报