Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return
"blue is sky the
".
思考:一开始没有考虑空格。去掉不合法空格+两次翻转,不需要额外空间。
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 |
class
Solution { public : void
reverseWords(string &s) { int
len=s.length(); int
i=0,j=len-1; //去掉前后空格 while (i<len&&s[i]== ‘ ‘ ) i++; while (j>=0&&s[j]== ‘ ‘ ) j--; len=j-i+1; s=s.substr(i,len); //去掉中间空格 for (i=0;i<s.length();i++) { if (s[i]== ‘ ‘ ) { j=i+1; while (s[j]== ‘ ‘ ) j++; s.erase(i+1,j-i-1); } } len=s.length(); for (i=0;i<len/2;i++) swap(s[i],s[len-i-1]); int
start=0; for (i=0;i<=len;i++) { if ((i<len&&s[i]== ‘ ‘ )||i==len) { for (j=start;j<(i+start)/2;j++) swap(s[j],s[i-(j-start)-1]); start=i+1; } } } }; |
[LeetCode]Reverse Words in a String,布布扣,bubuko.com
[LeetCode]Reverse Words in a String
原文:http://www.cnblogs.com/Rosanna/p/3590601.html