Skip to content

Commit c779756

Browse files
committed
🚀 16-Jul-2020
1 parent 1def10b commit c779756

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Given an input string, reverse the string word by word.
2+
3+
4+
5+
Example 1:
6+
7+
Input: "the sky is blue"
8+
Output: "blue is sky the"
9+
Example 2:
10+
11+
Input: " hello world! "
12+
Output: "world! hello"
13+
Explanation: Your reversed string should not contain leading or trailing spaces.
14+
Example 3:
15+
16+
Input: "a good example"
17+
Output: "example good a"
18+
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
19+
20+
21+
Note:
22+
23+
A word is defined as a sequence of non-space characters.
24+
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
25+
You need to reduce multiple spaces between two words to a single space in the reversed string.
26+
27+
28+
Follow up:
29+
30+
For C programmers, try to solve it in-place in O(1) extra space.
31+
32+
33+
34+
35+
36+
37+
38+
39+
class Solution {
40+
public:
41+
string reverseWords(string s) {
42+
stringstream str(s);
43+
string word, res="";
44+
while(str>>word){
45+
res = word + " " + res;
46+
}
47+
return res.substr(0, res.length()-1);
48+
}
49+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
Given an input string, reverse the string word by word.
2+
3+
4+
5+
Example 1:
6+
7+
Input: "the sky is blue"
8+
Output: "blue is sky the"
9+
Example 2:
10+
11+
Input: " hello world! "
12+
Output: "world! hello"
13+
Explanation: Your reversed string should not contain leading or trailing spaces.
14+
Example 3:
15+
16+
Input: "a good example"
17+
Output: "example good a"
18+
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
19+
20+
21+
Note:
22+
23+
A word is defined as a sequence of non-space characters.
24+
Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
25+
You need to reduce multiple spaces between two words to a single space in the reversed string.
26+
27+
28+
Follow up:
29+
30+
For C programmers, try to solve it in-place in O(1) extra space.
31+
32+
33+
34+
35+
36+
37+
38+
39+
class Solution {
40+
public:
41+
string reverseWords(string s) {
42+
stringstream str(s);
43+
string word, res="";
44+
while(str>>word){
45+
res = word + " " + res;
46+
}
47+
return res.substr(0, res.length()-1);
48+
}
49+
};

0 commit comments

Comments
 (0)