Skip to content

Commit 49a4899

Browse files
committed
Reverse words in a String
1 parent 67de492 commit 49a4899

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
We start traversing the string from the end until we hit a space. It indicates that we have gone past a word and now we need to store it.
2+
3+
We check if our answer variable is empty or not
4+
5+
If it’s empty, it indicates that this is the last word we need to print, and hence, there shouldn’t be any space after this word.
6+
7+
If it’s empty we add it to our result with a space after it. Here’s a quick demonstration of the same
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
string reverseWords(string s) {
4+
int left = 0;
5+
int right = s.length()-1;
6+
7+
string temp="";
8+
string ans="";
9+
10+
//Iterate the string and keep on adding to form a word
11+
//If empty space is encountered then add the current word to the result
12+
while (left <= right) {
13+
char ch= s[left];
14+
if (ch != ' ') {
15+
temp += ch;
16+
} else if (ch == ' ') {
17+
if (ans!="") ans = temp + " " + ans;
18+
else ans = temp;
19+
temp = "";
20+
}
21+
left++;
22+
}
23+
24+
//If not empty string then add to the result(Last word is added)
25+
if (temp!="") {
26+
if (ans!="") ans = temp + " " + ans;
27+
else ans = temp;
28+
}
29+
30+
return ans;
31+
}
32+
};

0 commit comments

Comments
 (0)