Single Stack + Regex Java Solution


  • 0
    A

    Slightly slower because of regex, but cleaner and more straight-forward code.

    public String decodeString(String s) {
            // default placeholder for cleaner code
            Stack<StringBuffer> stack = new Stack();
            stack.push(new StringBuffer());
            
            // regex, matching whole string
            Pattern p = Pattern.compile("^(\\d+)\\[(.*)]$");
            
            char prev = (char) 0;
            
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                
                if (Character.isDigit(ch) && !Character.isDigit(prev)) {
                    stack.push(new StringBuffer());
                }
                
                stack.peek().append(ch);
                prev = ch;
                    
                if (ch == ']') {
                    StringBuffer encoded = stack.pop();
                    Matcher m = p.matcher(encoded.toString());
                    
                    m.find();
                    int count = Integer.parseInt(m.group(1));
                    String pattern = m.group(2);
                    
                    StringBuffer parent = stack.peek();
                    
                    // generate pattern
                    for (int j = 0; j < count; j++) parent.append(pattern);
                }
            }
    
            // default string
            return stack.pop().toString();
        }
    

Log in to reply
 

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