Sunday, July 19, 2015

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.

string里面可能有前缀后缀和words中间的多余空格,要做到in-place,需要先对string里面的空格字符进行处理,再reverse, 所以这个题目分为两个部分, 1. deduplicate spaces, 2. reverse words in the string.

class Solution {
private:
    void reverse1(string &s, int left, int right) {
        while (left < right) {
            swap(s[left], s[right]);
            left++;
            right--;
        }
    }
public:
    void reverseWords(string &s) {
        //sanity check
        if (s.size() == 0) return;
        int slow = 0;
        int fast = 0;
        for (; fast < s.size(); fast++) {
            if (s[fast] == ' ' && (fast == 0 || s[fast-1] == ' ')) {
                continue;
            }
            s[slow++] = s[fast];
        }
        if (slow > 0  && s[slow-1] == ' ') s.resize(slow-1);
        else s.resize(slow);
        slow = 0;
        fast = 0;
        if (s.size() == 0) return;
        for (; fast < s.size(); fast++) {
            if (s[fast] == ' ') {
                reverse1(s, slow, fast-1);
                slow = fast+1;
            }
        }
        reverse1(s, slow, fast-1);
        reverse(s.begin(), s.end());
        return;
    }
};

No comments:

Post a Comment