LeetCode 394. Decode String
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string inside the square brackets is being repeated exactly k
times. Note that k
is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k
. For example, there will not be input like 3a
or 2[4]
.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
method
遍历字符串有4种情况
- 数字就
num
累计 - 字母
res
也累计 - 遇到左括号
[
,就把数字和字母入栈 - 遇到右括号
]
,把数字栈弹出为count
,当前res
重复count
次,累计到字符串栈上去,然后弹出为res
string decodeString(string s) {
stack<int> nums;
stack<string> strs;
int num = 0;
string res = "";
for (int i = 0; i < s.size(); i++) {
if (isdigit(s[i])) {
num = num * 10 + s[i] - '0'; // num累计
}
else if (isalpha(s[i])) {
res = res + s[i]; // res累计
}
else if (s[i] == '[') { // num和res入栈
nums.push(num);
num = 0;
strs.push(res);
res = "";
}
else {
int count = nums.top(); // 弹出重复次数
nums.pop();
for (int j = 0; j < count; j++) {
strs.top() += res; // res重复count次,累计到栈顶
}
res = strs.top(); // 弹出为res
strs.pop();
}
}
return res;
}