Skip to content

Commit ec754da

Browse files
author
Adam Lin
committed
Recursive
1 parent fb87288 commit ec754da

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

394_decodeString.cpp

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
//https://www.youtube.com/watch?v=qB0zZpBJlh8
2+
3+
class Solution {
4+
public:
5+
string decodeString(string s) {
6+
stack<string> stk; // Initialize a stack to store characters, numbers, and intermediate results
7+
8+
for(int i = 0; i < s.size(); ++i){
9+
if(s[i] != ']'){
10+
// If the current character is not ']', push it onto the stack
11+
stk.push(string(1, s[i]));
12+
} else {
13+
// When we encounter a ']', we need to decode the substring inside the brackets
14+
string substr = "";
15+
// Pop characters until we find the matching '['
16+
while(stk.top() != "["){
17+
substr = stk.top() + substr; // Build the substring in correct order
18+
stk.pop();
19+
}
20+
stk.pop(); // Remove the '[' from the stack
21+
22+
// Now, we need to find the number (could be more than one digit) before the '['
23+
string k = "";
24+
while(!stk.empty() && isdigit(stk.top()[0])){
25+
k = stk.top() + k; // Build the number in correct order
26+
stk.pop();
27+
}
28+
int num = stoi(k); // Convert the string number to an integer
29+
30+
// Repeat the substring 'num' times
31+
string repeatedStr = "";
32+
for(int j = 0; j < num; ++j){
33+
repeatedStr += substr;
34+
}
35+
// Push the repeated substring back onto the stack
36+
stk.push(repeatedStr);
37+
}
38+
}
39+
40+
// Build the final result from the stack
41+
string res = "";
42+
while(!stk.empty()){
43+
res = stk.top() + res; // Build the result in correct order
44+
stk.pop();
45+
}
46+
return res; // Return the decoded string
47+
}
48+
};
49+
50+
// Recursive solution
51+
class Solution {
52+
public:
53+
int i = 0; // Class member to keep track of index
54+
55+
string decode(string& s) {
56+
string result = "";
57+
int num = 0;
58+
while (i < s.size()) {
59+
char c = s[i];
60+
if (isdigit(c)) {
61+
num = num * 10 + (c - '0');
62+
i++;
63+
} else if (c == '[') {
64+
i++; // Move past '['
65+
string decoded = decode(s);
66+
// Repeat and append
67+
while (num > 0) {
68+
result += decoded;
69+
num--;
70+
}
71+
num = 0;
72+
} else if (c == ']') {
73+
i++; // Move past ']'
74+
return result;
75+
} else {
76+
result += c;
77+
i++;
78+
}
79+
}
80+
return result;
81+
}
82+
83+
string decodeString(string s) {
84+
i = 0; // Reset index before starting
85+
return decode(s);
86+
}
87+
};
88+
/*
89+
decode("3[a2[c]]", 0)
90+
|
91+
+-- decode("3[a2[c]]", 2)
92+
|
93+
+-- decode("3[a2[c]]", 5)
94+
| - 返回 ("c", 7)
95+
- 返回 ("acc", 8)
96+
- 返回 ("accaccacc", 8)
97+
98+
*/

0 commit comments

Comments
 (0)