557.Reverse Words in a String
557.Reverse Words in a String
难度:Easy
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1: 输入: "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
代码如下:
1
class Solution {
2
public:
3
string reverseWords(string s) {
4
vector<string> words;
5
words.push_back(" ");
6
for(auto w:s)
7
{
8
if(w==' ')
9
{
10
words.push_back(" ");
11
}
12
else
13
words[words.size()-1]+=w;
14
// cout<< words[words.size()-1]<<endl;
15
}
16
words[words.size()-1]=words[words.size()-1].substr(1,words[words.size()-1].length()-1);
17
// cout<< words[0]<<words[1]<<endl;
18
// words[words.size()-1]+=' ';
19
string res;
20
for(auto w:words)
21
{
22
for(int i=w.length()-1;i>=0;i--)
23
{
24
res+=w[i];
25
// cout<<res;
26
}
27
}
28
return res;
29
}
30
};
Copied!
Copy link