lintcode--Expression Expand

题目: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.

样例

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

解答:解答本题 有两点:(1)用栈做DFS,注意栈不为空,并且栈是先进后出的,注意顺序;(2)numbers可能是多位数。


class Solution {
public:
    /**
     * @reverse the word, include words and numbers
     */
    void reverseWord(string &s) {
        for (int i = 0, j = s.size() - 1; i < j; i++,j--) {
            swap(s[i], s[j]);
        }
    }
    /**
     * @param s  an expression includes numbers, letters and brackets
     * @return a string
     */
    string expressionExpand(string& s) {
        // Write your code here
        stack<char> res;
        string val = "";
        int len = s.length();
        if (len == 0) {
            return val;
        }
        for (int i = 0; i < len; i++) {
            if (s[i] == ']') {
                string tmp = "";
                while (!res.empty()) {
                    char ch = res.top();
                    res.pop();
                    if (ch == '[') {
                        break;
                    }
                    tmp += ch;
                }
                string num = "";
                while (!res.empty()) {
                    char tmpnum = res.top();
                    res.pop();
                    if(isdigit(tmpnum)){
                        num += tmpnum;
                    } else {
                        res.push(tmpnum);
                        break;
                    }
                }
                reverseWord(num);
                int count = atoi(num.c_str());
                string mid = "";
                reverseWord(tmp);
                for (int j = 0; j <count; j++) {
                    mid += tmp;
                }
                for (int j = 0; j < mid.length(); j++) {
                    res.push(mid[j]);
                }
            }
            else {
                res.push(s[i]);
            }
        }
        
        while (!res.empty()) {
            val += res.top();
            res.pop();
        }
        reverseWord(val);
        return val;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值