20. Valid Parentheses的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/85244891

题目描述:https://leetcode.com/problems/valid-parentheses/

括号匹配的规则很简单,每当碰上一个右括号,离它最近的左括号必须和它匹配。所以用栈的算法即可。注意遇到右括号时要判断栈内是不是空了,匹配完后也要检查栈内还有没有剩下的。

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

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/85244891
今日推荐