Reverse Words in a String

Reverse Words in a String

题目描述:

给定一个字符串,要求逆序字符串中的单词。

例子:

具体描述见LeetCode151

解题思路:

主要的思路是我们将字符串中的每个单词都逆序,然后整体全部逆序,这样就可以得到逆序单词的字符串序列了。需要注意的地方是我们需要判断边界和需要resize字符串的长度。

代码如下:

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
class Solution {
public:
void reverseWords(string &s) {
int i = 0;
int j = 0;//用来记录字符串中非空的长度
int l = 0;
int length = s.size();
int wordcount = 0;
while(true){
while(i < length && s[i] == ' ')i++;
//过滤掉空格
if (i == length) break;
//如果已经到达末尾
if (wordcount) s[j++] = ' ';
l = j;
while(i < length && s[i] != ' '){
s[j] = s[i];
i++;
j++;
}//l用来记录单词的起始位置
reverseword(s, l, j - 1);
//逆序单词
wordcount++;
}
s.resize(j);
reverseword(s, 0, j - 1);
}
//逆序函数用于逆序函数中从start到end位置的字符
void reverseword(string& s, int start, int end){
while(start < end){
swap(s[start], s[end]);
start++;
end--;
}
}
};