Decode String

Given an encoded string, return it's decoded string.

The encoding rule is:k[encoded_string], where theencoded_stringinside the square brackets is being repeated exactlyktimes. Note thatkis guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers,k. For example, there won't be input like3aor2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

用了个 Stack将字符串翻转

class Solution {
    public String decodeString(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        int number = 0;
        Stack<Object> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                number = number * 10 + c - '0';
            }else if (c == '[') {
                stack.push(number);
                number = 0;
            }else if(c == ']') {
                String str = combineStr(stack);
                Integer time = (Integer)stack.pop();
                for (int i = 0; i < time; i++) {
                    stack.push(str);
                }

            }else {
                stack.push(String.valueOf(c));
            }
        }
        return combineStr(stack);
    }
    public String combineStr(Stack<Object> stack) {
        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();
    }

}

results matching ""

    No results matching ""