Created
September 14, 2014 16:30
-
-
Save zsh-89/338635b9d71147ee375d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void reverseWords(string &s) { | |
int N = s.size(); | |
string ans(N + 1, '\0'); | |
int state = 0; | |
bool first_word = true; | |
int j = 0; | |
for (int i = N - 1; i >= 0; --i) { | |
if (state == 0 && s[i] != ' ') | |
state = 1; | |
if (state == 1) { | |
if (s[i] != ' ' && i != 0) | |
continue; | |
if (first_word) | |
first_word = false; | |
else | |
ans[j++] = ' '; | |
int sidx; | |
if (s[i] == ' ') | |
sidx = i + 1; | |
else if (i == 0) | |
sidx = 0; | |
j = proc(ans, j, s, sidx); | |
state = 0; | |
} | |
} | |
ans[j] = '\0'; | |
s = ans.c_str(); | |
} | |
int proc(string &ans, int j, const string &src, int i) { | |
for (; i<src.size() && src[i] != ' '; ++i) | |
ans[j++] = src[i]; | |
return j; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment