557. 反转字符串中的单词 III
class Solution {
public:
string reverseWords(string s) {
s+=' '; //为了让最后一个单词进入循环
string tempstr,res;
vector<string> vecstr;
for(char c:s){
if(c==' '){
reverse(tempstr.begin(), tempstr.end());
vecstr.push_back(tempstr);
tempstr.clear();
}else {
tempstr+=c;
}
}
for(int i=0;i<vecstr.size();i++){
res+=vecstr[i];
res+=' ';
}
res.pop_back(); //去除最后一个空格
return res;
}
};
优化
class Solution {
public:
string reverseWords(string s) {
s+=' '; //为了让最后一个单词进入循环
string tempstr,res;
for(char c:s){
if(c==' '){
reverse(tempstr.begin(), tempstr.end());
res+=tempstr;
res+=' ';
tempstr.clear();
}else {
tempstr+=c;
}
}
res.pop_back(); //去除最后一个空格
return res;
}
};