算法1
顺序存入(vector)每一个单词,逆序输出即可
C++ 代码
class Solution {
public:
string reverseWords(string s) {
vector<string> result;
string temp = "";
for(int i=0;i<s.size();i++){
if(s[i]!=' '){
temp += s[i];
}else{
result.push_back(temp);
temp = "";
}
if(i==s.size()-1){
result.push_back(temp);
}
}
if(result.size()==0){
return "";
}
string res = result[result.size()-1];
for(int i=result.size()-2;i>=0;i--){
res += " " + result[i];
}
return res;
}
};