Skip to content

Commit d6d35bf

Browse files
committed
reverse_words_in_a_string
1 parent be7bb93 commit d6d35bf

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
134134
#### [148. sort list](https://github.com/hitzzc/go-leetcode/tree/master/sort_list)
135135
#### [149. Max Points on a Line](https://github.com/hitzzc/go-leetcode/tree/master/max_points_on_a_line)
136136
#### [150. evaluate reverse polish notation](https://github.com/hitzzc/go-leetcode/tree/master/evaluate_reverse_polish_notation)
137+
#### [151. reverse words in a string](https://github.com/hitzzc/go-leetcode/tree/master/reverse_words_in_a_string)
137138

138139

139140

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <string>
2+
#include <iostream>
3+
#include <vector>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
void reverseWords(string &s) {
9+
vector<string> words;
10+
bool found = false;
11+
int start = -1;
12+
const char space = ' ';
13+
for (int i = 0; i < s.size(); ++i){
14+
if (found && s[i]==space){
15+
words.push_back(s.substr(start, i-start));
16+
found = false;
17+
}else if (!found && s[i]!=space){
18+
start = i;
19+
found = true;
20+
}
21+
}
22+
if (found) words.push_back(s.substr(start));
23+
s.clear();
24+
if (words.empty()) return;
25+
for (int i = words.size()-1; i > 0; --i){
26+
s += words[i];
27+
s.push_back(space);
28+
}
29+
s += words[0];
30+
return;
31+
}
32+
};

0 commit comments

Comments
 (0)