Reverse Words in a String

2019-05-25 22:56:44 浏览数 (1)

1. Description

2. Solution

  • First Try
代码语言:javascript复制
class Solution {
public:
    void reverseWords(string &s) {
        removeSpace(s);
        reverseWords(s, 0, s.size() - 1);
        int index = -1;
        int start = 0;
        while((index = s.find(" ", index   1)) != string::npos) {
            reverseWords(s, start, index - 1);
            start = index   1;
        }
        reverseWords(s, start, s.size() - 1);
    }

    void reverseWords(string& s, int start, int end) {
        for(int i = start, j = end; i < j; i  , j--) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }
    }

    void removeSpace(string &s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ")   1);
        int i = 0;
        int j = 1;
        while(j < s.size()) {
            if(s[j] == ' ' && s[j - 1] != ' ') {
                i = j;
            }
            if(s[j] == ' ' && s[j   1] != ' ' && i != j) {
                s.erase(i   1, j - i);
                j = i;
            }
            j  ;
        }
    }
};
  • Second Try
代码语言:javascript复制
class Solution {
public:
    void reverseWords(string &s) {
        reverseWords(s, 0, s.size() - 1);
        removeAndRemoveMiddleSpace(s);
    }

    void reverseWords(string& s, int start, int end) {
        for(int i = start, j = end; i < j; i  , j--) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }
    }

    void removeAndRemoveMiddleSpace(string &s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ")   1);
        int i = 0;
        int j = 1;
        int k = 0;
        while(j < s.size()) {
            if(s[j] == ' ' && s[j - 1] != ' ') {
                reverseWords(s, k, j - 1);
                i = j;
            }
            if(s[j] == ' ' && s[j   1] != ' ') {
                if(i != j) {
                    s.erase(i   1, j - i);
                    j = i;
                }
                k = j   1;
            }
            j  ;
        }
        reverseWords(s, k, j - 1);
    }
};

0 人点赞