【三次过】Lintcode 575. 字符串解码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/89203363

给出一个表达式 s,此表达式包括数字,字母以及方括号。在方括号前的数字表示方括号内容的重复次数(括号内的内容可以是字符串或另一个表达式),请将这个表达式展开成一个字符串。

样例

样例1

输入: S = abc3[a]
输出: "abcaaa"

样例2

输入: S = 3[2[ad]3[pf]]xyz
输出: "adadpfpfpfadadpfpfpfadadpfpfpfxyz"

挑战

你可以不通过递归的方式完成展开吗?


解题思路:

利用栈解题。注意这里将数字与字符一起入栈,遇到右括号时将从栈顶到第一个数字之间的字符出栈组合成字符串,然后再出栈第一个数字设为times, 最后入栈times次数的字符串,如此往复。

public class Solution {
    /**
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    public String expressionExpand(String s) {
        // write your code here
        if(s.length() <= 0)
            return "";
        
        //存储Integer和Character两种类型
        Stack<Object> stack = new Stack<>();
        
        int num = 0;
        for(char c : s.toCharArray()){
            if(Character.isDigit(c)){
                num = num * 10 + c - '0';   //求出数字的值
            }else if(c == '['){
                stack.push(num);    //将数字入栈
                num = 0;
            }else if(c == ']'){
                String str = popStack(stack);  
                int times = (int)stack.pop();
                
                //重新入栈times次str
                for(int i=0; i<times; i++)
                    for(int j=0; j<str.length(); j++)
                        stack.push(str.charAt(j));
            }else{  //字母则直接入栈
                stack.push(c);
            }
        }
        
        return popStack(stack);
    }
    
    //返回stack中从栈顶开始的字符组合而成的字符串,遇到非字符时截止
    private String popStack(Stack<Object> stack){
        StringBuilder sb = new StringBuilder();
        Stack<Character> stackTemp = new Stack<>();
        
        while(!stack.isEmpty() && stack.peek() instanceof Character)
            stackTemp.push((Character)stack.pop());
        
        while(!stackTemp.isEmpty())
            sb.append(stackTemp.pop());
        
        return sb.toString();
    }

}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/89203363