跳转至

394.字符串解码 (Medium)*

题目描述*

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

示例*

s = "3[a]2[bc]", 返回 "aaabcbc".

s = "3[a2[c]]", 返回 "accaccacc".

s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".

代码*

使用辅助栈实现,保存重复次数 times,当前结果字符串 res,每遇到 [ 时入栈,遇到 ] 时出栈。

class Solution {
public:
    string repeatStr(string target, int times) {
        string res = "";
        while(times--) {
            res += target;
        }
        return res;
    }
    string decodeString(string s) {
        string res = "";
        if(s.length() == 0) {
            return res;
        }
        int times = 0;
        stack<pair<int, string>> st;
        for(auto c : s) {
            if(c >= '0' && c <= '9') {
                times = times * 10 + c - '0';
            }else if(c == '[') {
                st.push({times, res});
                res = "";
                times = 0;
            }else if(c == ']') {
                auto tmp = st.top();
                st.pop();
                res = tmp.second + ((tmp.first == 0) ? "" : repeatStr(res, tmp.first));
            }else {
                res += c;
            }
        }
        return res;
    }
};

最后更新: July 23, 2022