-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseWordsInAString.h
53 lines (52 loc) · 1.07 KB
/
ReverseWordsInAString.h
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
52
53
/**
* Solution 1
* time: O(n) space: O(1)
*
*/
class Solution {
public:
void reverseWords(string &s)
{
string res("");
for(int i=s.size()-1;i>=0;--i)
{
while(i>=0&&s[i]==' ')--i;
if(i<0)break;
if(!res.empty())res.push_back(' ');
string str;
while(i>=0&&s[i]!=' ')str.push_back(s[i--]);
reverse(str.begin(),str.end());
res.append(str);
}
s=res;
return;
}
};
/**
* Solution 2
* time: O(n) space: O(1)
* 利用stringstream+getline来分割单词
*/
class Solution {
public:
void reverseWords(string &s) {
if(s.empty())return;
string s1(""),s2("");
stringstream ss(s);
while(getline(ss,s2,' '))
{
if(s2=="")continue;
string s3(s2.rbegin(),s2.rend());
s1+=s3;
s1+=' ';
}
if(s1.empty())
{
s="";
return;
}
string s4(s1.rbegin(),s1.rend());
s=s4.substr(1);
return;
}
};