20. 有效的括号 (栈 难度1) 详细题解

题目链接
在这里插入图片描述
栈的经典教学级题目了

class Solution {
public:
    bool isValid(string s) {
        if(s.length()%2 == 1)
            return false; //剪枝
        stack<char> tmp;
        
        for(int i = 0; i < s.length(); i++){
            if(tmp.empty() || s[i]=='(' || s[i]=='[' || s[i]=='{')
                tmp.push(s[i]);
            else if((tmp.top()=='('&&s[i]==')') || (tmp.top()=='['&&s[i]==']') || (tmp.top()=='{'&&s[i]=='}'))
                tmp.pop();
            else 
                tmp.push(s[i]);
        }
        
        if(tmp.empty())
            return true;
        else 
            return false;
    }
};

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/85029809