lintcode(575)Expression Expand

Description:

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.

Explanation:

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?

Solution:

Reverse traversal.  倒序遍历字符串,如果遇到‘]’, count(层数)+1,将之后的字符串添加到list[count]中,直到遇到‘[’,然后计算重复次数,按照次数执行复制后,将结果添加到list的上一层中。最后list[0]即为结果。主要添加字符时,要添加到前面(倒序遍历)。

public class Solution {
    /**
     * @param s  an expression includes numbers, letters and brackets
     * @return a string
     */
    public String expressionExpand(String s) {
        // Write your code here
        int index = s.length() - 1;
        ArrayList<String> res = new ArrayList<String>();
        res.add("");
        int count = 0;
        while(index >= 0){
            if(s.charAt(index) == ']'){
                res.add("");
                count++;
                index--;
            }
            else if(s.charAt(index) == '['){
                index--;
                int time = 0;
                String t = "";
                while(index >= 0 && s.charAt(index) - '0' >= 0 && s.charAt(index) - '0' <= 9){
                    t = s.charAt(index) + t;
                    index--;
                }
                for(int j = 0;j<t.length();j++){
                    time = time*10 + (t.charAt(j) - '0');
                }
                for(int i = 0;i<time;i++){
                    res.set(count - 1 , res.get(count) + res.get(count - 1) );
                }
                res.set(count , "");
                count--;
            }
            else {
                res.set(count , s.charAt(index) + res.get(count));
                index--;
            }
        }
        return res.get(0);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值