LintCode 575: Decode String (Stack经典难题!)

  1. Decode String
    Given an expression s includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.

Example
s = abc3[a] return abcaaa
s = 3[abc] return abcabcabc
s = 4[ac]dy, return acacacacdy
s = 3[2[ad]3[pf]]xyz, return adadpfpfpfadadpfpfpfadadpfpfpfxyz

Challenge
Can you do it without recursion?

思路:
这个感觉挺难。思路是用两个stack,一个维护string,一个维护number。但是不容易调通。
注意:

  1. 遇到’]'就把两个stack都pop出来。
  2. 遇到’['就把两个stack都push进去,因为新的string开始了。但要记得把num和str都clear。
  3. str是当前的string。topStr是之前的string,一旦topStr pop出来,要根据num (即count)来和当前的str相加。

代码如下:

class Solution {
public:
    /**
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    string expressionExpand(string &s) {
        stack<int> stackNum;
        stack<string> stackStr;
        
        string result;
        string str;
        int num = 0;
        
        int len = s.size();

        for (int i = 0; i < len; ++i) {
            if ((s[i] >= '0') && (s[i] <= '9')) {

                num = num * 10 + s[i] - '0';

            } else if (s[i] == ']') {

                int count = stackNum.top();
                stackNum.pop();
                string topStr = stackStr.top();
                stackStr.pop();

                for (int i = 0; i < count; ++i) {
                    topStr += str;     
                }
                str = topStr;

            } else if (s[i] == '[') {  //new str starts

                stackNum.push(num);
                stackStr.push(str);
                num = 0;
                str.clear();

            } else {

                str = str + s[i];  //read the letters into str

            }
          
        }

        return str;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值