LeetCode: 557. Reverse Words in a String III

题目描述

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

1
2
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

这题需要先根据' '来切分字符串,然后对每一个切分后的元素进行反转,反转可以用reverse(s.begin(), s.end())

切分字符串的时候,我使用了字符串流,然后使用getline函数来进行切割。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
private:
vector<string> split(string s, char d){
vector<string> result;
stringstream input(s);
string tmp;

while (getline(input, tmp, d)) {
if (tmp == "") {
continue;
}
result.push_back(tmp);
}
return result;
}

public:
string reverseWords(string s) {
vector<string> split_s = split(s, ' ');
string result = "";
for (int i=0; i < split_s.size(); i++) {
reverse(split_s[i].begin(), split_s[i].end());
result = result + split_s[i];
if (i < split_s.size()-1) {
result += " ";
}
}
return result;
}
};