-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode151_reverse_words_in_a_string.cpp
80 lines (70 loc) · 1.86 KB
/
leetcode151_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* leecode161_reverse_words_in_a_string.cpp
* @author wangguibao ([email protected])
* @date 2023/06/15 15:29
* @brief https://leetcode.com/problems/reverse-words-in-a-string
*/
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
std::vector<std::string> sVec;
split(s, sVec);
int wordCnt = sVec.size();
for (size_t i = 0; i < wordCnt; ++i) {
std::cout << std::quoted(sVec[i]) << std::endl;
}
std::string ret;
for (int i = wordCnt - 1; i >= 0; --i) {
if (i < wordCnt - 1) {
ret += " ";
}
ret += sVec[i];
}
return ret;
}
private:
void split(std::string s, std::vector<std::string>& sVec) {
int b = 0;
int e = s.length();
int curBegin = b;
bool bFound = false;
while (b < e) {
if (s[b] == ' ') {
if (bFound) {
sVec.emplace_back(s.substr(curBegin, b - curBegin));
bFound = false;
}
} else {
if (!bFound) {
bFound = true;
curBegin = b;
}
}
++b;
}
if (bFound) {
sVec.emplace_back(s.substr(curBegin));
}
return;
}
};
int main()
{
while (1) {
std::string s;
std::cout << "Input string (Ctrl-C to exit):" << std::endl;
if (!std::getline(std::cin, s)) {
return 0;
}
std::cout << s << std::endl;
Solution solution;
auto ret = solution.reverseWords(s);
std::cout << ret << std::endl;
}
return 0;
}