[Leet] - 20. Valid Parentheses [stack] - c++

ha·2022년 2월 8일
0

LeetCode

목록 보기
20/21

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

C++ stack(괄호)

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

0개의 댓글