Leetcode典型题解答和分析、归纳和汇总——T20(有效的括号)

题目描述:

给定一个只包括 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

题目解析:

该题采用堆栈的方式来求解是简单的。

class Solution{
    public:
    bool isValid(string s){
        stack<char>  res;
        int len = s.size();
        if(len==0)  return true;  //空字符串,返回真
        if(len%2==1) return false; //字数为奇数,无法配对
        for(int i=0;i<len;i++)
        {
            if(res.empty())  //如果res栈为空
            {
                res.push(s[i])
                continue;
            }
            if((res.top()=='('&&s[i]==')')||(res.top()=='['&&s[i]==']')||(res.top()=='{'&&s[i]=='}'))
            {
                res.pop(); //匹配上了,则弹出
                continue;
            }
            res.push(s[i]);
            

        }
        return res.empty();  //当堆栈为空,则返回为真
    }
};
发布了56 篇原创文章 · 获赞 7 · 访问量 4489

猜你喜欢

转载自blog.csdn.net/weixin_44504987/article/details/104308049