Algorithm/PTUStudy

8주차. 스택, 큐(유효한 괄호)

지구우중 2023. 3. 30. 18:23

20. 유효한 괄호

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

 

Valid Parentheses - LeetCode

Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam

leetcode.com

📌문제
괄호로 된 입력값이 올바른지 판별하라



- 예제1
  📝입력

Input: s = "()[]{}"



  💻출력

Output: true



 - 예제2

  📝입력
 

Input: s = "(]"



  💻출력

Output: false


    
📌풀이(스택)

2ms, 40.2mb

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for(char c : s.toCharArray()){
        if(c == '(') stack.push(')');
        else if(c == '[') stack.push(']');
        else if(c == '{') stack.push('}');
        else{
            if(stack.isEmpty() || stack.pop() != c) return false;
        }
    }
    return stack.isEmpty();
}

그닥 어렵지 않은 문제였다.