[LeetCode] Valid Parentheses 풀이

내 풀이

  • 시간복잡도
    • O(N)
  • 공간복잡도
    • O(N)
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (char ch : s.toCharArray()) {
            if (ch == ')' || ch == '}' || ch == ']') {
                if (stack.isEmpty()) {
                    return false;
                }

                char peeked = stack.peek();
                if (ch == ')' && peeked == '(') {
                    stack.pop();
                    continue;
                }

                if (ch == '}' && peeked == '{') {
                    stack.pop();
                    continue;
                }

                if (ch == ']' && peeked == '[') {
                    stack.pop();
                    continue;
                }
                return false;
            } else {
                stack.push(ch);
            }
        }

        return stack.isEmpty();
    }
}

최적화

  • 시간복잡도
    • O(N)
  • 공간복잡도
    • O(N)
  • peek을 pop으로 변경하여 중복 호출을 줄였다.
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (char ch : s.toCharArray()) {
            switch (ch) {
                case ')':
                    if (stack.isEmpty() || stack.pop() != '(') return false;
                    break;
                case '}':
                    if (stack.isEmpty() || stack.pop() != '{') return false;
                    break;
                case ']':
                    if (stack.isEmpty() || stack.pop() != '[') return false;
                    break;
                default:
                    stack.push(ch);
            }
        }

        return stack.isEmpty();
    }
}

'Algorithms > 문제풀이' 카테고리의 다른 글

[LeetCode] Roman to Integer 풀이  (2) 2024.09.02
[LeetCode] Palindrome Number 풀이  (0) 2024.08.27
[LeetCode] Two Sum 풀이  (0) 2024.08.27
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유