-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path186. Reverse-Words-in-a-String-II
54 lines (49 loc) · 1.21 KB
/
186. Reverse-Words-in-a-String-II
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
class Solution {
public:
/**
* @param str: a string
* @return: return a string
*/
string reverseWords(string &str) {
// write your code here
string res = "";
int i = 0;
int j = str.length() - 1;
while(true){
int i = j;
while(i >= 0 && str[i] != ' ')
i--;
string word = str.substr(i+1,j - i);
res = res + word + " ";
j = i-1;
if (j < 0)
break;
}
res.pop_back();
return res;
}
};
class Solution {
public:
/**
* @param str: a string
* @return: return a string
*/
string reverseWords(string &str) {
// write your code here
for(int start = 0, end = 0; end < str.length(); end += 1){
if(str[end] == ' '){
reverse(str,start,end-1);
start = end + 1;
}else if(end == str.length() - 1){
reverse(str,start,end);
}
}
reverse(str,0,str.length()- 1);
return str;
}
void reverse(string& str, int left, int right){
while(left < right)
swap(str[left++],str[right--]);
}
};