Simple Java Solution with one Stack


  • 0
    S
    public class Solution {
        public String decodeString(String s) {
            StringBuilder num = new StringBuilder();
            StringBuilder result = new StringBuilder();
            Stack<String> st = new Stack();
            int i = 0;
            while(i < s.length()) {
                while(s.charAt(i) <= '9' && s.charAt(i) >= '0') {
                    num.append(s.charAt(i++));
                }
                if(s.charAt(i) == ']') {
                    while(st.peek().matches("[a-zA-Z]+")) {
                        result.insert(0, st.pop()+"");
                    }
                    st.push(repeat(st.pop(), result.toString()));
                    result = new StringBuilder();
                }
                else if(s.charAt(i) != '['){
                    st.push(s.charAt(i)+"");
                } else if(s.charAt(i) == '['){
                    st.push(num.toString());
                    num = new StringBuilder();
                }
                i++;
            }
            result = new StringBuilder();
            while(!st.isEmpty()) {
                result.insert(0, st.pop()); 
            }
            return result.toString();
        }
        
        private String repeat(String num, String s) {
            int numInt = Integer.parseInt(num);
            StringBuilder result = new StringBuilder();
            for(int i = 0; i < numInt; i++) {
                result.append(s);
            }
            return result.toString();
        }
    }

Log in to reply
 

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