/
151_ReverseWordsInAString.cpp
65 lines (58 loc) · 1.29 KB
/
151_ReverseWordsInAString.cpp
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
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
//在有多余空格的情况下还是有问题
void reverseWords(string &s) {
int length = s.size();
if (length == 0)
return;
trim(s);
//cout << s << endl;
Reverse(s, 0, length-1);
int start = 0;
int end = 0;
while (s[start] != '\0'){
if (s[start] == ' '){
++start;
++end;
}
if (s[end] == ' ' || s[end] == '\0'){
Reverse(s, start, --end);
start = ++end;
}
else {
++end;
}
}
}
private:
void Reverse(string& str, int start, int end){
while (start < end){
Swap(&str[start], &str[end]);
++start;
--end;
}
}
void Swap(char* i, char* j){
char temp = *i;
*i = *j;
*j = temp;
}
//去除前后空格
void trim(string& str){
if (!str.empty()){
str.erase(0,str.find_first_not_of(' '));
str.erase(str.find_last_not_of(' ') + 1);
}
}
};
int main()
{
string str = "the sky is blue";
Solution solu;
solu.reverseWords(str);
cout << str << endl;
return 0;
}