-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodeString.cpp
More file actions
85 lines (62 loc) · 1.83 KB
/
decodeString.cpp
File metadata and controls
85 lines (62 loc) · 1.83 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class Solution {
private:
string repeat(string s, int n) {
string repeat;
for (int i = 0; i < n; i++)
repeat += s;
return repeat;
}
bool isNum(char num)
{
return (num >= 48 && num <= 57);
}
bool isLetter(char letter)
{
return (letter >= 97 && letter <= 122);
}
public:
string decodeString(string s) {
string decoded = "";
vector<string> stack;
int n = s.length();
for(int i = 0; i < n; i++)
{
if(s[i] != '[' && s[i] != ']')
{
if(isdigit(s[i]))
{
string temp = "";
while(isdigit(s[i]))
{
temp += s[i];
i++;
}
stack.push_back(temp);
}
else
{
string chr (1, s[i]);
stack.push_back(chr);
}
}
else if(s[i] == ']')
{
string temp = "";
while(!isdigit(stack.back()[0]))
{
temp = stack.back() + temp;
stack.pop_back();
}
temp = repeat(temp, stoi(stack.back()));
stack.pop_back();
stack.push_back(temp);
}
}
while(!stack.empty())
{
decoded = stack.back() + decoded;
stack.pop_back();
}
return decoded;
}
};