leetcode 20 parenthesis match

来源:互联网 发布:macbook装windows教程 编辑:程序博客网 时间:2024/04/30 16:44

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.

class Solution {public:    bool isValid(string s) {        typedef string::size_type sz;        sz size = s.size();        map<char, char> mp = { {')', '('}, {']', '['}, {'}', '{'}}; // make_pair(')', '(');        typedef map<char, char>::const_iterator miter;        vector<char> v;        v.reserve(size);        typedef vector<char>::const_iterator viter;        for (sz i = 0; i != size; ++i) {            char tmp = s[i];            miter mit =  mp.find(tmp);            if (mit == mp.end())                v.push_back(tmp);            else {                if (mit->second == *(v.rbegin()))                    v.pop_back();                else                    return false;            }        }        if (v.empty()) return true;        return false;    }}; // runtime distribution 9.93%

参考后

class Solution {public:    bool isValid(string s) {        typedef string::size_type sz;        sz size = s.size();        stack<char> intStack;        typedef vector<char>::const_iterator viter;        for (sz i = 0; i != size; ++i) {            char tmp = s[i];            switch (s[i]){                case '(' :                case '[' :                case '{' :                     intStack.push(s[i]);                    break;                case ')' :                    if (intStack.empty() || '(' != intStack.top())                        return false;                    else                       intStack.pop();                     break;                case ']' :                    if (intStack.empty() || '[' != intStack.top())                        return false;                    else                       intStack.pop();                    break;                case '}':                    if (intStack.empty() || '{' != intStack.top())                        return false;                    else                       intStack.pop();                    break;            }        }        if (intStack.empty()) return true;        return false;    }}; // runtime distribution 9.93%