Skip to content

Commit 5f381b5

Browse files
Create reverse_words_in_string.cpp
1 parent be6fd15 commit 5f381b5

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

reverse_words_in_string.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
string reverseWords(string s) {
4+
5+
string result = "";
6+
int i = 0, N = s.length();
7+
8+
while(i < N) {
9+
while(i < N && s[i] == ' ') i++;
10+
if(i >= N) break;
11+
12+
int j = i + 1;
13+
14+
while(j < N && s[j] != ' ')
15+
j++;
16+
17+
string substr = s.substr(i, j-i);
18+
if(result.length() == 0) {
19+
result = substr;
20+
}
21+
else result = substr + " " + result;
22+
i = j + 1;
23+
}
24+
25+
return result;
26+
}
27+
};

0 commit comments

Comments
 (0)