-
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
69 lines (60 loc) · 1.34 KB
/
Reverse_Words_in_a_String.cpp
File metadata and controls
69 lines (60 loc) · 1.34 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/
// Author : zheng yi xiong
// Date : 2014-11-10
/**********************************************************************************
*
* Given an input string, reverse the string word by word.
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
* Clarification:
* 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.
*
**********************************************************************************/
class Solution {
public:
void reverseWords(string &s) {
if (s.empty())
{
return;
}
string str = s;
int alphaNum = 0;
s.clear();
for (int i = str.length() - 1; i >= 0; --i)
{
if (' ' == str[i])
{
if (0 < alphaNum)
{
s.append(&str[i + 1], alphaNum);
s.append(&str[i], 1);
alphaNum = 0;
}
}
else
{
++alphaNum;
}
}
if (' ' != str[0])
{
s.append(&str[0], alphaNum);
}
else
{
if (s.length() > 0)
{
if (' ' == s[s.length() - 1])
{
s.erase(s.length() - 1, 1);
}
}
}
}
};