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

 

Example 1:

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"
Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"

Example 4:

Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"

 

Constraints:

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

 

思路:

遇到这种左右括号要一一对应,比较容易想到的是用stack。观察可以得出,数字和字符串肯定是要分离的,其次外部的字符串和括号内的字符串也应该是分离的,因为外部可能不会增长,而内部会重复几次,随括号前的数字而定。但是这个字符串之间的分离又不能只是简单的用两个字符串来解决,因为当多个重叠括号如[[[]]]这种情况,两个字符串是不够的,结合前面,想到用stack<string>来分离。同样的,数字用stack<int>,那么再加上当前的字符串和当前的数字,就有了四个变量来记录。读取原字符串时:每一个char都是四种情况之一:数字,字母,'[' 和 ']'。对于数字和字母,分别加到当前的记录变量上去,要注意数字是按十进制的,因为每次应该要先自身乘10再加上当前读到的数字。遇到 '[' 时,这个括号里可能是有新的数字和字符串的,因此需要隔离,将当前数字和字符串各自存进stack中,然后将当前数字和字符串清零。遇到 ']' , 这时候就需要清算了。首先是当前手里的字符串肯定需要重复当前手里的数字次数,但是考虑到可能括号里没有括号,即单个括号的情况,这时候当前手里的数字是被清0的,因为之前遇到了 '[' ,把数字存入stack后清0了,所以这里重复的次数应该是stack<int>中的top位置的数字。这之后考虑到括号内有括号的情况,如例2里的 "3[a2[c]]",假设处理完内括号,此时手上的字符串已经是"cc"了,而它应该是与这个 'a' 是同一档的,因此要把stack<string>中top位置的 'a' 给加上来,然后再继续下一轮处理第二个 ’]‘ 。

 

代码:

class Solution {
public:
    string decodeString(string s) {
        stack<string> record;
        stack<int> nums;
        string res;
        int num = 0;
        for (auto c : s)
        {
            if (isdigit(c))
                num = num*10+ c - '0';
            else if (isalpha(c))
                res.push_back(c);
            else if (c == '[')
            {
                nums.push(num);
                num = 0;
                record.push(res);
                res.clear();
            }
            else //]
            {
                string temp = res;
                for (int i = 0; i < nums.top()-1; i++)
                    res += temp;
                nums.pop();
                res = record.top() + res;
                record.pop();
            }
        }
        return res;
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值