[Stack, Medium] Decode String

송재호·2025년 3월 13일
0

https://leetcode.com/problems/decode-string/description/?envType=study-plan-v2&envId=leetcode-75

인풋이 제대로 되어있다고 가정하므로 고민할 것은 많이 줄었다.
일단 다른 문제와 마찬가지로 stack문제기 때문에 되도록이면 stack 자료구조를 쓴다.

  • 인코딩된 body는 '['가 나올때까지 pop하면 알 수 있음 (스택이므로 reverse해야 원본 알 수 있음)
  • 인코딩할 times는 숫자가 아닌 값이 나올때까지 pop하면 알 수 있음 (스택이므로 *= 10 누적해야 원본 숫자 만들 수 있음)

메모리랑 런타임 모두 상위권은 아니다.
개선할 수 있는 점: 어차피 시작은 정방향 순회기 때문에 굳이 스택에 다 때려넣은다음 역순으로 계산할 필요가 없다. 스택에는 필요한 값만 넣으면 훨씬 줄일 수 있다.

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

        for (char c : s.toCharArray()) {
            if (c == ']') {

                // find body
                StringBuilder encodedBody = new StringBuilder();
                while (!stack.isEmpty()) {
                    char current = stack.pop();
                    if (current == '[') {
                        break;
                    }
                    encodedBody.append(current);
                }

                // find times
                int times = 0;
                int digits = 1;
                while (!stack.isEmpty()) {
                    if (!Character.isDigit(stack.peek())) {
                        break;
                    }
                    int currentDigit = Character.getNumericValue(stack.pop());
                    times += currentDigit * digits;
                    digits *= 10;
                }
                
                String decoded = encodedBody.reverse().toString();

                for (int i=0; i<times; i++) {
                    for (char decodedChar : decoded.toCharArray()) {
                        stack.push(decodedChar);
                    }
                }
            } else {
                stack.push(c);
            }
        }

        StringBuilder answer = new StringBuilder();
        while (!stack.isEmpty()) {
            answer.append(stack.pop());
        }
        return answer.reverse().toString();
    }
}
profile
식지 않는 감자

0개의 댓글