-
Notifications
You must be signed in to change notification settings - Fork 10
/
Day-114.cpp
70 lines (65 loc) · 1.84 KB
/
Day-114.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
//
// Created by Amit Kumar on 19/03/23.
//
#include "stack"
#include "queue"
#include "vector"
#include "iostream"
using namespace std;
bool isAlpha(const char &ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
string reverseString(const string &str) {
stack<string> words; // alphabetic words
queue<string> delimiters; // continuous string of delimiters
int start{}, end{};
bool beginningByDelimiter{false};
while (end < (int) str.size()) {
if (isAlpha(str[start])) {
while (end < (int) str.size() && isAlpha(str[end])) {
end++;
}
words.push(str.substr(start, end - start));
} else {
if (start == 0) {
beginningByDelimiter = true;
}
while (end < (int) str.size() && !isAlpha(str[end])) {
end++;
}
delimiters.push(str.substr(start, end - start));
}
start = end;
}
// We have separated the word & delimiters from the string.
// only confusion is where to start build our result string.
// i.e. what should appended first a word or a delimiter ?
// for this we'll use beginningByDelimiter variable :-)
string result{};
while (!words.empty() || !delimiters.empty()) {
if (beginningByDelimiter) {
result += delimiters.front();
delimiters.pop();
beginningByDelimiter = false;
} else {
if (!words.empty()) {
result += words.top();
words.pop();
}
if (!delimiters.empty()) {
result += delimiters.front();
delimiters.pop();
}
}
}
return result;
}
int main() {
vector<string> testStrings = {"hello/world:here", "hello/world:here/", "hello//world:here",
"//hello//", "//hello//world//here//"};
// Let's test
for (auto &str: testStrings) {
cout << "Input: " << str << " Output: " << reverseString(str) << endl;
}
return 0;
}