394. Decode String

Problem:

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; 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".

思路

Solution (C++):

string decodeString(string s) {
    stack<string> ch;
    stack<int> nums;
    string res = "";
    int num = 0;
    
    for (char c : s) {
        if (isdigit(c)) {
            num = num*10 + c-'0';
        }
        else if (isalpha(c)) {
            res += c;
        }
        else if (c == '[') {
            ch.push(res);
            nums.push(num);
            res = "";
            num = 0;
        }
        else {
            string tmp = res;
            for (int i = 0; i < nums.top()-1; ++i) {
                res += tmp;
            }
            res = ch.top() + res;
            ch.pop(); nums.pop();
        }
    }
    return res;
}

性能

Runtime: 0 ms  Memory Usage: 6.7 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12668177.html