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



#### seems like my code currently couldn't handle the "  " case.....hmmm....

#include <string>
#include <iostream>
using namespace std;

// Let's first assume that there is no extra space.
void reverseWord(string& s, int i, int j) {
    while(i < j) {
        swap(s[i], s[j]);
        i++;
        j--;
    }
}

// secondly, we can add extra space before or after.
void removeSpaces(string& s) {
    int i = 0, j = 0, spaceCount = 0;
    while(i < s.size()) {
        if(s[i] == ' ') {
            i++;
            spaceCount++;
        } else {
            if(spaceCount >= 1) {
                s[j++] = ' ';
                spaceCount = 0;
            }
            s[j++] = s[i++];
        }
    }
    s[j] = '\0';
    if(s[0] == ' ') s = s.substr(1, j - 1);
}

void reverseWords(string& s) {
    if(s.size() <= 1) return;
    removeSpaces(s);
    reverseWord(s, 0, s.size() - 1);
    // we then reverse the word one by one.
    int i = 0, j = 0;
    while(j <= s.size()) {
        if(s[j] != ' ' && s[j] != '\0') {
            j++;
        } else {
            reverseWord(s, i, j - 1);
            j++;
            i = j;
        }
    }
}

int main(void) {
    string words = "  abc   dc";
    removeSpaces(words);
    reverseWords(words);
    cout << words << endl;
}



你可能感兴趣的:(LeetCode 151. Reverse Words in a String)