My cpp solution 0ms by hashmap


  • 0
    V
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> st;
            map<char,char> ma;
            ma['(']=')';
            ma['{']='}';
            ma['[']=']';
            for(int i = 0;i<s.length();i++){
                if(s[i]=='('||s[i]=='['||s[i]=='{'){
                    st.push(s[i]);
                }else{
                    if(st.empty()||ma[st.top()]!=s[i])return false;
                    st.pop();
                }
            }
            if(st.empty())return true;
            return false;
        }
    };

Log in to reply
 

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