"Valid Parentheses" Solution in C++


  • 0
    M
    #include <stack>
    #include <set>
    #include <map>
    using namespace std;
    
    static set<char> c_open = {'(', '{', '['};
    static map<char, char> c_corresp = {{')', '('}, {'}', '{'}, {']', '['},};
    
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> st;
            for (size_t i = 0; i < s.size(); ++i) {
                char c = s[i];
                if (c_open.find(c) != c_open.end()) st.push(c);
                else {
                    if (st.empty() || st.top() != c_corresp[c]) return false;
                    st.pop();
                }
            }
            return st.empty();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.