LeetCode557 Reverse Words in a String III

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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.

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

样例

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

思路

将句子中的单词翻转(单词之间以空格隔开)

模拟一下,记录每个单词的起始位置和长度,然后翻转即可

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
// 字符串翻转函数
string rev(string s) {
int l = 0, r = s.size() - 1;
while (l < r) swap(s[l++], s[r--]);
return s;
}
string reverseWords(string s) {
string str;
// 变量p记录单词起始位置
for (int i = 0, p = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
str += rev(s.substr(p, i - p)) + ' ';
p = i + 1;
}
// 特判字符串末尾
if (i == s.size() - 1) str += rev(s.substr(p));
}
return str;
}
};
分享到 评论