20. Valid Parentheses

来源:互联网 发布:什么软件看美剧最全 编辑:程序博客网 时间:2024/06/16 06:23

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

bool isValid(string s) {    if (s == "")return false;    stack<char> res;    unordered_map<char, char> mapsign = { { ')', '(' }, { '}', '{' }, { ']', '[' } };    for (int i = 0; i < s.size(); i++){        if (s[i] == '(' || s[i] == '{' || s[i] == '[')res.push(s[i]);        else {            if (!res.empty()){                if (mapsign[s[i]] == res.top())res.pop();                else return false;            }            else return false;        }    }    if (!res.empty())return false;    else return true;}