forked from jnozsc/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_Words_in_a_String.cpp
More file actions
51 lines (47 loc) · 1.23 KB
/
Copy pathReverse_Words_in_a_String.cpp
File metadata and controls
51 lines (47 loc) · 1.23 KB
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
/*
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Example
Clarification Expand
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
*/
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Solution {
/**
* @param s : A string
* @return : A string
*/
public:
string reverseWords(string s) {
// write your code here
if (s.empty()) {
return "";
}
vector<string> tokens;
stringstream ss(s);
string item;
while (getline(ss, item, ' ')) {
if (!item.empty()) {
tokens.push_back(item);
}
}
if (tokens.size() == 0) {
return "";
}
string result = "";
for (int i = tokens.size() - 1; i >= 0; i--) {
result += (tokens[i] + " ");
}
return result.substr(0, result.length() - 1);
}
};