原题:https://leetcode.com/problems/decode-string/description/
Given an encoded string, return it’s 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; 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 won’t be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
这个问题可以用栈解决。创建两个栈,栈st用于存储当前已经得到的字符串,栈num用于存储每个方括号内字符串重复的次数。遍历输入的字符串:
如果是数字,则将其压入num;
如果是字母和’[‘,则压入st;
如果是’]’,则开始出栈,直到遇到’[为止,将出栈的字符按出栈顺序的反序组成字符串再次压入st中,继续遍历。
当输入字符串遍历完后,栈st中就是所得到的字符串结果。
class Solution {
public:
string decodeString(string s) {
string ss;
stack<char> st;
stack<int> num;
for (int i = 0; i < s.size(); i++) {
if (s[i] >= 'a'&&s[i] <= 'z' || s[i] == '[') {
st.push(s[i]);
}
if (s[i] >= '0'&&s[i] <= '9') {
string nums;
while (s[i] >= '0'&&s[i] <= '9') {
nums += s[i]; i++;
}
i--;
num.push(atoi(nums.c_str()));
}
if (s[i] == ']') {
string tmp, temp;
int times = num.top();
num.pop();
while (st.top() != '[') {
tmp = st.top() + tmp;
st.pop();
}
st.pop();
while (times--) {
temp += tmp;
}
for (int i = 0; i < temp.size(); i++) {
st.push(temp[i]);
}
}
}
string temp;
while (!st.empty()) {
ss += st.top();
st.pop();
}
reverse(ss.begin(), ss.end());
return ss;
}
};
27 / 27 test cases passed.
Status: Accepted
Runtime: 0 ms