Decode String

Posted flagyuri

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Decode String相关的知识,希望对你有一定的参考价值。

public class Solution {
    /**
     * @param s: an expression includes numbers, letters and brackets
     * @return: a string
     */
    public String expressionExpand(String s) {
        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(Integer.valueOf(num));
                num = 0;
            } else if (c == ‘]‘) {
                String newStr = popStack(stack);
                Integer count = (Integer) stack.pop();
                for (int i = 0; i < count; i++) {
                    stack.push(newStr);
                }
            } else {
                stack.push(String.valueOf(c));
            }
            
        }
        return popStack(stack);
    }
    
    private String popStack(Stack<Object> stack) {
        // pop stack until stack is empty or get a number
        Stack<String> buffer = new Stack<>();
        while (!stack.isEmpty() && (stack.peek() instanceof String)) {
            buffer.push((String) stack.pop());
        }
        
        StringBuilder sb = new StringBuilder();
        while (!buffer.isEmpty()) {
            sb.append(buffer.pop());
        }
        return sb.toString();
    }
}

  

Description

Given an expression s contains 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.

Numbers can only appear in front of “[]”.

Example

Example1

Input: S = abc3[a]
Output: "abcaaa"

Example2

Input: S = 3[2[ad]3[pf]]xyz
Output: "adadpfpfpfadadpfpfpfadadpfpfpfxyz"

思路:递归实现 or 非递归实现。
   对于非递归实现,使用栈来解决。遇见“【“将数字放入栈中,遇见“】”将栈中的字符弹出,直到栈为空,或遇见数字,当遇见的是普通的字符,直接放入栈中。

 

 
 

以上是关于Decode String的主要内容,如果未能解决你的问题,请参考以下文章

AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法

decode-string

394. Decode String

394. Decode String

PHP中的html_entity_decode问题?

Leetcode: Decode String