0ms solution without using stack


  • 0
    M
    class Solution {
    public:
        bool isValid(string s) {
            int top = 0;
            int n = s.size();
            unordered_map<char, char> mp;
            mp[')'] = '('; mp[']'] = '['; mp['}'] = '{';
            for(int i = 0; i < n; ++i){
                if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
                    s[top++] = s[i];
                }
                else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
                    if(top == 0) return false;
                    else if(mp[s[i]] != s[--top]) return false;
                }
                else return false;
            }
            return top == 0 ? true : false;
        }
    };

Log in to reply
 

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