Reverse Words in a String 单词取反
[email protected]
Question:
Given an input string s, reverse the string word by word.
For example, given s = "the sky is blue", return "blue is sky the".
void reverseWords(string &s) {
vector <string>des;
if(s.empty())
return;
int len = s.size();
for(int i = 0; i < len; i++){
if(s[i] == ‘ ‘)
continue;
string word;
while(i < len && s[i] != ‘ ‘){
word += s[i];
i++;
}
des.push_back(word);
}
reverse(des.begin(), des.end());
if(des.empty())
s = "";
else {
s.clear();
int j ;
for(j = 0; j < des.size() -1; j++){
s += des[j];
s += ‘ ‘;
}
s += des[j];
}
}
时间: 2024-10-16 05:02:41