for Robot Artificial Inteligence

48. Valid Parentheses

|

class Solution {
public:
    bool isValid(string s) {
        if (s.empty())
            return true;
        stack<char> database;

        for(char n : s)
        {
            if(n =='(' || n=='[' || n=='{')
            {
                database.push(n);
            }
            else
            {
                if(database.empty()) return false;
                if(n == ')' && database.top()!='(') return false;
                if(n == ']' && database.top()!='[') return false;
                if(n == '}' && database.top()!='{') return false;

                database.pop();
            }
        }
        return database.empty();


    }
};

Comments