My accepted C++ 2ms code.


  • 0
    G
     class Solution {
        public:
            bool isValid(string s) {
                stack<char> sc;
                int len=s.length();
                for(int i=0;i<len;i++){
                    if(s[i]=='(' || s[i]==')' || s[i]=='{' || s[i] == '}' || s[i]== '[' || s[i]==']' ){
                        if(sc.empty()){
                            sc.push(s[i]);
                        }else{
                            if(s[i]-sc.top()==1||s[i]-sc.top()==2){
                                sc.pop(); 
                            }else{
                                sc.push(s[i]);
                            }
                        }
                    }
                }
                if(sc.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.