본문 바로가기
LeetCode

20. Valid Parentheses 문제풀이

by O_x 2022. 7. 13.
20. Valid Parentheses
Easy
14119658Add to ListShare

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 same type of brackets.
  2. Open brackets must be closed in the correct order.

다음과 같은 경우 입력 문자열이 유효합니다.

1. 열린 대괄호는 동일한 유형의 대괄호로 닫아야 합니다.
2. 열린 대괄호는 올바른 순서로 닫아야 합니다.

 

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'

 

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(auto p:s){
            if(p=='{' || p =='[' || p=='(') st.push(p); // { ( [ 방향으로 들어 온 것만 push
            else {
                if(st.size()==0) return false; // 첫번째 갈호가 방향이 틀리면 return false
                char top = st.top(); // 값 복사 
                if( top == '(' && p == ')' ) st.pop(); // 헷갈릴순 있는 부분이다
                //push된 것을 잘 생각 해보면 { [ ( 만 push된 것을 알 수 있다.
                else if( top == '{' && p == '}' ) st.pop();
                else if( top == '[' && p == ']' ) st.pop();
                else return false;
            }
        }return st.size() == 0;
    }
};

운영중인 카톡방입니다.

https://open.kakao.com/o/gsMhUFie

 

C/C++/C# 언리얼/유니티 /질문

#C++#C#언리얼#게임개발#질문#개발#자료구조#백준#프로그래머스#c#유니티#unity#enreal

open.kakao.com

 

'LeetCode' 카테고리의 다른 글

242. Valid Anagram C++문제 풀이  (0) 2022.07.20
387. First Unique Character in a String 문제풀이  (0) 2022.07.19
415. Add Strings 문제 c++  (0) 2022.07.10
125. Valid Palindrome 문제  (0) 2022.07.10
796. Rotate String 문제  (0) 2022.07.07

댓글