-
Notifications
You must be signed in to change notification settings - Fork 1
/
394+Decode String_Stack.cpp
44 lines (40 loc) · 1.25 KB
/
394+Decode String_Stack.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
class Solution {
public:
int getDigit(string &src, size_t &ptr) {
int res = 0;
while (ptr < src.size() && isdigit(src[ptr])) {
res = res * 10 + src[ptr] - '0';
ptr++;
}
return res;
}
string decodeString(string s) {
stack<int> numSt;
stack<string> stringSt;
string res;
int numT;
size_t ptr = 0;
while (ptr < s.size()) {
char cur = s[ptr];
if (cur == '[') {
ptr++;
numSt.push(numT);
stringSt.push(res);
res = "";
} else if (cur == ']') {
ptr++;
string tmpSrc;
int times = numSt.top(); numSt.pop();
while (times--) //复制字符串res
tmpSrc += res;
res = stringSt.top() + tmpSrc; stringSt.pop(); //把他拼到前一个字符串上,并且重新赋值给 res,相当于解耦]右括号
} else if (isdigit(cur)) {
numT = getDigit(s, ptr);
} else if (isalpha(cur)) {
ptr++;
res += cur;
}
}
return res;
}
};