lintcode(575)Expression Expand

来源:互联网 发布:西南大学远程网络培训 编辑:程序博客网 时间:2024/06/07 19:04

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);    }}