清风的技术小屋

不为所动, 做更专业的自己

0%

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"

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

Related Topics: String

原问题:557. Reverse Words in a String III

解决方案

题目主要意思是反转字符串中的每一个单词,因此这道题目主要是找到单词的位置,这里我们可以设定两个指针,分别命名为startend,指针start指向单词的第一个字母的位置,指针end指向单词的最后一个字母的位置,然后将[start, end]里面的单词反转即可。至于指针怎么设置,我们可以先设置指针start指向第一个字母,然后找到空格字符的前一个字符的位置赋给指针end;接着找到下一个字母的位置赋给指针start,然后找到下一个空格字符的位置,将该空格字符的前一个字符的位置赋给指针end,如此循环,直到字符串被遍历完。

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
string reverseWords(string s)
{
int start, end;
char tmp;

start = 0;
end = s.size();
for (int i=0; i<s.size(); i++) {
if (s[i] == ' ') {
end = i - 1;

// reverse word
while (start < end) {
tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}

while (i < s.size() && s[i] == ' ')
i++;
start = i;
}
}

// process last word
end = s.size() - 1;
while (start < end) {
tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}

return s;
}
};

int main()
{
Solution solu;
string str1 = "Let's take LeetCode contest";

cout << str1 << endl;
cout << solu.reverseWords(str1) << endl;

return 0;
}