557.Reverse Words in a String

557.Reverse Words in a String

难度:Easy

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例 1: 输入: "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

代码如下:

class Solution {
public:
string reverseWords(string s) {
vector<string> words;
words.push_back(" ");
for(auto w:s)
{
if(w==' ')
{
words.push_back(" ");
}
else
words[words.size()-1]+=w;
// cout<< words[words.size()-1]<<endl;
}
words[words.size()-1]=words[words.size()-1].substr(1,words[words.size()-1].length()-1);
// cout<< words[0]<<words[1]<<endl;
// words[words.size()-1]+=' ';
string res;
for(auto w:words)
{
for(int i=w.length()-1;i>=0;i--)
{
res+=w[i];
// cout<<res;
}
}
return res;
}
};