LeetCode394. Decode String

原题: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值