Java clear solution using String of StringBuilder


  • 0
    S
    class Solution {
        public String decodeString(String s) {
            Stack<StringBuilder> stack = new Stack<>();
            Stack<Integer> countStack = new Stack<>();
            
            int index = 0;
            int n = s.length();
            char[] str = s.toCharArray();
            StringBuilder res = new StringBuilder();
            while (index < n) {
                if (Character.isDigit(str[index])) {
                    int count = 0;
                    while (index < n && Character.isDigit(str[index])) {
                        count = 10 * count + (str[index++] - '0');
                    }
                    countStack.push(count);
                } else {
                    if (str[index] == '[') {
                        stack.push(new StringBuilder());
                    } else if (str[index] == ']') {
                        int repeat = countStack.pop();
                        String segment = stack.pop().toString();
                        StringBuilder sb = stack.isEmpty()? res : stack.peek();
                        for (int i = 0; i < repeat; i++) {
                            sb.append(segment);
                        }
                    } else {
                        StringBuilder sb = stack.isEmpty()? res : stack.peek();
                        sb.append(str[index]);
                    }
                    index++;
                }
            }   
            
            return res.toString();
        }
    }
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.