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

问题需要维护两个栈,一个数字栈一个字符栈。同时遇到“20[ab]时,这里的数字是20,避免取错。这里主要是当遇到 ']’  时,需要将在数字栈中将数字取出,同时把相应的字符在字符栈中取出。将字符转换为string的话,用stringstream进行转换。具体代码如下:

class Solution {
public:
    /**
     * @param s  an expression includes numbers, letters and brackets
     * @return a string
     */
    string expressionExpand(string& s) {
        // Write your code here
        int length = s.size();
        stack<int> s_numbers;
        stack<char> s_chars;
        int save_num = 0;
        for(int i = 0;i!=length;++i){
            if(isNumber(s[i])){
                save_num = save_num*10+s[i]-'0';
                continue;
            }
            else if(s[i]=='['){
                s_numbers.push(save_num);
                save_num = 0;//计数重新清零
                s_chars.push(s[i]);
            }
            else if(s[i]==']'){
                int times = s_numbers.top();
                s_numbers.pop();
                vector<char> temp_chars;
                while(s_chars.top()!='['){
                    temp_chars.push_back(s_chars.top());
                    s_chars.pop();
                }
                //弹出[]
                s_chars.pop();
                for(int time=1;time<=times;++time){
                    for(int i = temp_chars.size()-1;i>=0;--i){
                        s_chars.push(temp_chars[i]);               
                    }
                }
            }
            else{
                s_chars.push(s[i]);
            }
        }
        //输出栈中的元素
		string res;
		stack<char> temp_char;
		stringstream ss;
		int stack_size = s_chars.size();
		for (int i = 0; i != stack_size; ++i){
				temp_char.push(s_chars.top());
				s_chars.pop();
		}
		for (int i = 0; i != stack_size; ++i){
			ss << temp_char.top();
			temp_char.pop();
		}
		ss >> res;
		return res;
    }
    bool isNumber(char c){
        int flag = c - '0';
        return flag >= 0 && flag <= 9;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值