题意:把一个句子中以空格隔开的单词分别反转
分析:字符串操作。注意去掉首尾的空字符
代码:
class Solution {
public:
void reverseWords(string &s) {
vector<string> str;
string t="";
while(s[0]==' '){
s.erase(0,1);
}
while(s[s.length()-1]==' '){
s.erase(s.length()-1,1);
}
int k=0;
int len=s.length();
while(k<len){
if(s[k]!=' '){
t+=s[k];
k++;
}else{
str.push_back(t);
t="";
k++;
while(s[k]==' '){
k++;
}
}
}
str.push_back(t);
s="";
for(int i=str.size()-1;i>0;--i){
s=s+str.at(i)+" ";
}
s+=str.at(0);
}
};