[LeetCode] 20. Valid Parentheses

김개발·2021년 11월 23일
0

LeetCode

목록 보기
2/10

문제 푼 날짜 : 2021-11-24

문제

문제 링크 : https://leetcode.com/problems/valid-parentheses/

접근 및 풀이

Stack 자료구조를 배울 때 빼놓을 수 없는 괄호 짝맞추기 문제였다.
워낙 많이 풀어본 문제여서 쉽게 풀 수 있었다.

코드

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        
        for (char ch : s) {
            if (ch == '(' || ch == '{' || ch == '[') {
                st.push(ch);
            } else {
                if (st.empty()) {
                    return false;
                } else {
                    if (ch == ')') {
                        if (st.top() != '(') {
                            return false;
                        } else if (st.top() == '(') {
                            st.pop();
                        }
                    } else if (ch == '}') {
                        if (st.top() != '{') {
                            return false;
                        } else if (st.top() == '{') {
                            st.pop();
                        }
                    } else if (ch == ']') {
                        if (st.top() != '[') {
                            return false;
                        } else if (st.top() == '[') {
                            st.pop();
                        }
                    }
                }
            }
        }
        if (!st.empty()) {
            return false;
        } else {
            return true;
        }
    }
};

결과

피드백

쉽다고 코드를 막 짜다가 틀려버렸다...
코드 짤 때 항상 신중하게 짜는 습관을 다시 들이도록 하자.

profile
개발을 잘하고 싶은 사람

0개의 댓글