String:20. Valid Parentheses

来源:互联网 发布:yaf 数据库 yii 编辑:程序博客网 时间:2024/05/17 16:00

class Solution {public:    bool isValid(string s) {        map<char, char> m = {{'}', '{'}, {')', '('}, {']', '['}};        stack<char> t;        if(s.size() == 0)        return false;        for(int i = 0; i < s.size(); ++i)        {        if(m.find(s[i]) != m.end())        {                if(t.empty())                {                    return false;                }        if(m[s[i]] != t.top())        {        return false;        }                else                {                    t.pop();                }        }        else        {        t.push(s[i]);        }        }        if(t.empty())        return true;        else        return false;    }};

    为什么我总是写这么长……而且总是有很多if语句…………看到别人写了一个看起来简单的java版本,改成C++:

class Solution {public:    bool isValid(string s) {        stack<char> charstack;        for(int i = 0; i < s.size(); ++i)        {            if(s[i] == '(')                charstack.push(')');            else if(s[i] == '{')                charstack.push('}');            else if(s[i] == '[')                charstack.push(']');            else if(charstack.empty() || charstack.top() != s[i])                return false;              else                 charstack.pop();        }        return charstack.empty();    }};
    这个看起来就逻辑清晰,我写的逻辑很乱。