LintCode:M-Expression Expand

58 篇文章 0 订阅
11 篇文章 0 订阅

LintCode链接


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


public class Solution {
    /**
     * @param s  an expression includes numbers, letters and brackets
     * @return a string
     */
    public String expressionExpand(String s) {
        String res = "";
        
        int n = s.length();
        //Stack<Integer> stackNum = new Stack<Integer>();
        Stack<String> stack = new Stack<String>();
        int i=0;
        while(i<n){
            char t = s.charAt(i);
            if(t<'0' || t>'9'){
                res+=String.valueOf(t);
                i++;
            }else{
                String tmp="";
                while(true){
                    //遇到第一个]前的字符串入栈
                    while(s.charAt(i)!=']'){
                        stack.add(String.valueOf(s.charAt(i)));
                        i++;
                    }
                    i++;//]的下一个字符
                    
                    //遇到第一个]
                    //弹出[]间的字符串
                    String sInside = "";
                    while(stack.peek().charAt(0)!='['){
                        sInside=stack.pop()+sInside;
                    }
                    stack.pop();//弹出'['
                    
                    //获得[]前的数字
                    String sNum = "";
                    while(!stack.isEmpty() && stack.peek().charAt(0)>='0' && stack.peek().charAt(0)<='9'){
                        sNum = stack.pop()+sNum;
                    }
                    int num = Integer.valueOf(sNum);
                    
                    //计算重复字符串
                    tmp = repeat(sInside, num);
                    
                    if(stack.isEmpty())
                        break;
                    else {
                    	if(num!=0)//容易忽略,num为0时,tmp="",不能入栈
                    		stack.add(tmp);
                    }  
                }
                res+=tmp;
            }
        }
        
        return res;
    }
    
    String repeat(String s, int num){
        String res="";
        while(num>0){
            res+=s;
            num--;
        }
        return res;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值