Problem Solving/LeetCode

[LeetCode] C++ 20. Valid Parentheses

LeeJaeJun 2024. 8. 18. 13:41
728x90
반응형

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

 

문제

 

문제 분석

- 스택을 이용해서 닫는 기호가 나타났을 때, 스택의 가장 최상단에 그와 연결되는 여는 기호가 있어야 유효한 Parenthesis가 될 수 있습니다. 

 

풀이

class Solution {
private:
    map<char, char> match = {
        {')', '('},
        {'}', '{'},
        {']','['}
    };
public:
    bool isValid(string s) {
        stack<char> stack;
        
        for(const auto& c: s){
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            }else{
                if(stack.empty()) {
                    return false;
                }

                char top = stack.top();
                stack.pop();

                if(match[c]!= top){
                    return false;
                }
            }
        }

        return stack.empty(); 
    }
};

728x90
반응형