(String, Easy) Valid Parentheses

송재호·2025년 8월 8일
0

https://leetcode.com/problems/valid-parentheses/description/

흔한 스택 문제
알고리즘 문제 푸는데 아무 영향 없겠지만 Stack은 동기화블록 오버헤드 있으므로 걍 Deque(ArrayDeque)씀

class Solution {
    public boolean isValid(String s) {
        
        Deque<Character> stack = new ArrayDeque<>();

        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                
                if (stack.isEmpty()) {
                    return false;
                }
                char p = stack.pop();
                
                if (c == ')' && p != '(') {
                    return false;
                }
                if (c == ']' && p != '[') {
                    return false;
                }
                if (c == '}' && p != '{') {
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }
}
profile
식지 않는 감자

0개의 댓글