-
Notifications
You must be signed in to change notification settings - Fork 0
/
151-ReverseWordsInAString.cpp
72 lines (68 loc) · 1.57 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
66
67
68
69
70
71
72
/*=============================================================================
# FileName: 151-ReverseWordsInAString.cpp
# Desc: AC 17ms
# Author: Jian Huang
# Email: huangjian1993@gmail.com
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-06-25 23:24:38
# History:
=============================================================================*/
#include <leetcode.h>
class Solution {
public:
void reverseWord(string &s,int start, int end) {
int i = start, j = end;
while (i < j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i ++;
j --;
}
return ;
}
void reverseWords(string &s) {
int start = 0, end = 0;
while (s[start] == ' ') {
start ++;
}
if (start == s.length()) {
s = "";
return ;
}
s = s.substr(start, s.length() - start);
end = s.length() - 1;
while (s[end] == ' ') {
end --;
}
s = s.substr(0, end + 1);
start = 0, end = 0;
while (1) {
while (end < s.length() && s[end] != ' ') {
end ++;
}
if (end == s.length()) {
reverseWord(s, start, end - 1);
break;
}
reverseWord(s, start, end - 1);
while (end < s.length() && s[end] == ' ') {
end ++;
}
start = end;
}
reverseWord(s, 0, s.length() - 1);
for (int i = 0; i < s.length() - 1; i ++) {
while (s[i] == ' ' && s[i + 1] == ' ') {
deleteCharAtIndex(s, i + 1);
}
}
return ;
}
void deleteCharAtIndex(string &s, int index) {
string temp = s.substr(0, index);
temp = temp + s.substr(index + 1, s.length() - index - 1);
s = temp;
}
};