Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.7 kB
3
Indexable
Never
class Solution {
    public String decodeString(String s) {
        Stack<String> st = new Stack<String>();
        int idx = s.length() - 1;

        while (idx >= 0) {
            String temp = "";
            if (Character.isLetter(s.charAt(idx))) {
                st.push(String.valueOf(s.charAt(idx)));
            } else if (s.charAt(idx) == ']') {
                while(!st.isEmpty() && !st.peek().equals("]")) {                    
                    temp += st.pop();
                }

                if (!temp.isEmpty()) {
                    st.push(temp);
                }
                
                st.push("]");
            } else if (s.charAt(idx) == '[') {
                int multiple = 1;
                String res = "";
                while(!st.isEmpty() && !st.peek().equals("]")) {
                    temp += st.pop();
                }

                String number = "";

                while (idx - 1 >= 0 && Character.isDigit(s.charAt(idx - 1))) {
                    number = String.valueOf(s.charAt(idx - 1)) + number;
                    idx--;
                }

                if (!number.isEmpty()) {
                    multiple = Integer.parseInt(number);
                }

                for (int i = 0; i < multiple; i++) {
                    res += temp;
                }

                if(!st.isEmpty() && st.peek().equals("]")) {
                    st.pop();
                }
                
                if (!res.isEmpty()) {
                    st.push(res);
                }
            }

            idx--;
        }

        String res = "";

        while (!st.isEmpty()) {
            res += st.pop();
        }

        return res;
    }

}
Leave a Comment