Java Solution Using Stack


  • 0
    K
    public String decodeString(String s) {
        StringBuilder sb = new StringBuilder();
        Stack<Object> st = new Stack<Object>();
        int len = s.length();
        int i = 0;
        boolean hasDigit = false;
        while (i < len) {
            char c = s.charAt(i);
            if (c == '[') {
                st.push(Integer.parseInt(sb.toString()));
                sb.setLength(0);
                hasDigit = false;
            } else if (c == ']') {
                while (st.peek() instanceof String) {
                    sb.insert(0, st.pop());
                }
                int count = (Integer)st.pop();
                st.push(new String(new char[count]).replace("\0", sb.toString()));
                sb.setLength(0);
            } else if (c >= '0' && c <= '9') {
                if (!hasDigit && sb.length() > 0) {
                    st.push(sb.toString());
                    sb.setLength(0);
                }
                sb.append(c);
                hasDigit = true;
            } else {
                sb.append(c);
            }
            i++;
        }
        while (!st.isEmpty()) {
            sb.insert(0, st.pop());
        }
        return sb.toString();
    }

Log in to reply
 

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