-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path394_decodeString.cpp
More file actions
98 lines (89 loc) · 2.93 KB
/
394_decodeString.cpp
File metadata and controls
98 lines (89 loc) · 2.93 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
86
87
88
89
90
91
92
93
94
95
96
97
98
//https://www.youtube.com/watch?v=qB0zZpBJlh8
class Solution {
public:
string decodeString(string s) {
stack<string> stk; // Initialize a stack to store characters, numbers, and intermediate results
for(int i = 0; i < s.size(); ++i){
if(s[i] != ']'){
// If the current character is not ']', push it onto the stack
stk.push(string(1, s[i]));
} else {
// When we encounter a ']', we need to decode the substring inside the brackets
string substr = "";
// Pop characters until we find the matching '['
while(stk.top() != "["){
substr = stk.top() + substr; // Build the substring in correct order
stk.pop();
}
stk.pop(); // Remove the '[' from the stack
// Now, we need to find the number (could be more than one digit) before the '['
string k = "";
while(!stk.empty() && isdigit(stk.top()[0])){
k = stk.top() + k; // Build the number in correct order
stk.pop();
}
int num = stoi(k); // Convert the string number to an integer
// Repeat the substring 'num' times
string repeatedStr = "";
for(int j = 0; j < num; ++j){
repeatedStr += substr;
}
// Push the repeated substring back onto the stack
stk.push(repeatedStr);
}
}
// Build the final result from the stack
string res = "";
while(!stk.empty()){
res = stk.top() + res; // Build the result in correct order
stk.pop();
}
return res; // Return the decoded string
}
};
// Recursive solution
class Solution {
public:
int i = 0; // Class member to keep track of index
string decode(string& s) {
string result = "";
int num = 0;
while (i < s.size()) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + (c - '0');
i++;
} else if (c == '[') {
i++; // Move past '['
string decoded = decode(s);
// Repeat and append
while (num > 0) {
result += decoded;
num--;
}
num = 0;
} else if (c == ']') {
i++; // Move past ']'
return result;
} else {
result += c;
i++;
}
}
return result;
}
string decodeString(string s) {
i = 0; // Reset index before starting
return decode(s);
}
};
/*
decode("3[a2[c]]", 0)
|
+-- decode("3[a2[c]]", 2)
|
+-- decode("3[a2[c]]", 5)
| - 返回 ("c", 7)
- 返回 ("acc", 8)
- 返回 ("accaccacc", 8)
*/