自己写的
class Solution {
public:
string reverseWords(string s) {
vector<string> words;
int i = 0;
while(s[i] == ' ' && i < s.length()){
i++;
}
while(i < s.length()){
string temp = "";
while(s[i] != ' ' && i < s.length()){
temp += s[i];
i++;
}
words.push_back(temp);
while(s[i] == ' ' && i < s.length()){
i++;
}
}
reverse(words.begin(), words.end());//实际上不需要这一步,反过来输出就行
string res = "";
for(string word : words){
res += word;
res += " ";
}
res = res.substr(0, res.length()-1);
return res;
}
};
如果想原字符数改,可以先去除头尾空格,然后字符串翻转,再翻转每一个单词
更简单的写法
class Solution {
public:
string reverseWords(string s) {
vector<string> temp;
// initializing stringstream object
stringstream str(s);
string words;
// storing each words in a vector
while(str >> words)
temp.push_back(words);
reverse(temp.begin(), temp.end());
string ans;
// storing character by character each word in reverse order
for(auto it : temp)
{
for(auto c : it)
ans.push_back(c);
ans.push_back(' ');
}
// deleting extra space
ans.pop_back();
return ans;
}
};