20. 有效的括号

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。

总结:
考虑不全面,通过测试点进行修补程序,比较浪费时间
思路:

  • 用栈
  • 边界排除:字符数为奇数个返回false
  • 遍历每一个字符:
  1. 若当前字符为左括号,则入栈;
  2. 若当前字符为右括号:没有左括号(即栈为空),返回false; 栈不为空但左右括号不匹配,false;
  3. 若当前字符为右括号且括号相匹配,则弹栈;
  4. 结束遍历后栈为空则返回true.
bool isValid(string s)
{
    stack<char> st;
    if(s.length()%2==1)
        return false;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]=='('||s[i]=='['||s[i]=='{')
        {
            st.push(s[i]);
        }
        if(st.empty()&&(s[i]==')'||s[i]==']'||s[i]=='}'))
            return false;
        if(!st.empty())
        {
            if(s[i]==')'&&st.top()!='('||s[i]==']'&&st.top()!='['||s[i]=='}'&&st.top()!='{')
                return false;
            if(s[i]==')'&&st.top()=='('||s[i]==']'&&st.top()=='['||s[i]=='}'&&st.top()=='{')
                st.pop();
        }

    }
    return st.empty();
}

利用哈希表键值存储匹配
unordered_map<char,char> pairs
pairs.count() 返回匹配特定键的元素数量

bool isValid(string s)
{
    stack<char> st;
    if(s.length()%2==1)
        return false;
    unordered_map<char,char> pairs={
            {')','('},
            {']','['},
            {'}','{'}
    };
    for(int i=0;i<s.length();i++)
    {
        if(pairs.count(s[i]))
        {
            if(st.empty()||pairs[s[i]]!=st.top())
                return false;
            st.pop();
        }
        else
        {
            st.push(s[i]);
        }
    }
    return st.empty();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值