코딩테스트

[leetcode] 394. Decode String

nayoon 2024. 7. 13. 23:05

링크

 

 

Stack과 정규식으로 범벅됨..

 

 

class Solution {
    public String decodeString(String s) {
        Stack<String> st = new Stack<>();

        String[] sp = s.split("");
        for(String c: sp) {
            if (c.equals("]")) {
                StringBuilder temp = new StringBuilder();
                while(true) {
                    if (st.peek().equals("[")) {
                        st.pop();
                        break;
                    } else {
                        temp.append(st.pop());
                    }
                }
                int k = Integer.parseInt(st.pop());
                for(int j = 0; j < k; j++) {
                    st.push(temp.toString());
                }
            } else {
                if (c.matches("^[0-9]*$") && st.size() > 0 && st.peek().matches("^[0-9]*$")) {
                    int t1 = Integer.parseInt(st.pop()) * 10 + Integer.parseInt(c);
                    st.push(Integer.toString(t1));
                } else {
                    st.push(c);
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        while(!st.empty()) {
            sb.append(st.pop());
        }
        sb.reverse();

        return sb.toString();
    }
}

'코딩테스트' 카테고리의 다른 글

[leetcode] 13. Roman to Integer  (0) 2024.07.19
[leetcode] 27. Remove Element  (0) 2024.07.18
[leetcode] 735. Asteroid Collision  (0) 2024.06.28
[leetcode] 162. Find Peak Element  (0) 2024.06.28
[leetcode] 2352. Equal Row and Column Pairs  (0) 2024.06.26