-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Words in a String.cpp
55 lines (42 loc) · 1.06 KB
/
Reverse Words in a String.cpp
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
class Solution {
public:
string reverseWords(string s) {
auto sourceSize = s.size();
string resultStr;
resultStr.reserve(sourceSize);
string str;
str.reserve(sourceSize / 2 );
auto concatStr = [](std::string &str1, std::string &str2)-> std::string {
if (str2.length() == 0)
return str1;
return str1 + " " + str2;
};
bool prevSymbol = false;
for (auto &c : s) {
bool isSpace = isspace(c) != 0;
if (isSpace && prevSymbol) {
resultStr = concatStr(str, resultStr);
str = "";
prevSymbol = false;
continue;
}
else if (isSpace)
{
continue;
}
prevSymbol = true;
str += c;
}
if (str.length() != 0) {
resultStr = concatStr(str, resultStr);
}
return resultStr;
}
void checkValue(string input, string expected)
{
auto result = reverseWords(input);
if (result != expected) {
throw new runtime_error("Failed on \"" + input + "\" Expected: " + expected);
}
}
};