Reverse Words in a String II
LeetCode #186
Description:
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
Example:
Note
Idea:
操,比Reverse words in a string简单多了!
Code:
void reverseWords(string &s) {
int i=0, j; // left and right of one word
int icurr=0; // current copy position
int n=s.size();
while(i!=n){
while(i!=n && s[i]==' '){ // Until non space is found
++i;
}
j=i;
while(j!=n && s[j]!=' '){ // Until space is found
j++;
}
if(i!=n){
reverseSingleWord(s, i, j-1); // reverse one word
}
while(i!=j){ // Copy one word
s[icurr++] = s[i++];
}
icurr++;
}
reverseSingleWord(s, 0, s.size()-1); // reverse the whole sentence
}
void reverseSingleWord(string &s, int i, int j){
while(i<j){
swap(s[i], s[j]);
i++;
j--;
}
}