【Leetcode栈与队列】20. 有效的括号



Leetcode20

1.问题描述

在这里插入图片描述


2.解决方案

解法一:通过分析不匹配情况进行代码实现

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    bool isValid(string s) {
        stack<int> st;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') st.push(')');
            else if (s[i] == '{') st.push('}');
            else if (s[i] == '[') st.push(']');
            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
            else if (st.empty() || st.top() != s[i]) return false;
            else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
        }
        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
        return st.empty();
    }
};



解法二:栈

在这里插入图片描述

主要是两处判断要想到,对应两种特殊情况
1.第一处是如果有 “}}” 这种情况
2.第二处对应遍历完栈还没空的情况

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

                //bool a=s[i]==')'&&st.top()=='(';
                //bool b=s[i]==']'&&st.top()=='[';
                //bool c=s[i]=='}'&&st.top()=='{';

                if((s[i]==')'&&st.top()=='(')||(s[i]==']'&&st.top()=='[')||(s[i]=='}'&&st.top()=='{')) st.pop();
                else return false;
            }
        }

        if(st.empty()== false) return false;
        return true;
    }
};



解法三:栈(官方优化)

优化点:
1.如果是奇数个直接return false

if (n % 2 == 1) {
	return false;
}

2.使用了unordered_map更加快速匹配左右括号
3.增强for,还可以很优雅,自己经常忘记用

for (char ch: s) 


class Solution {
public:
    bool isValid(string s) {
        int n = s.size();
        if (n % 2 == 1) {
            return false;
        }

        unordered_map<char, char> pairs = {
            {')', '('},
            {']', '['},
            {'}', '{'}
        };
        stack<char> stk;
        for (char ch: s) {
            if (pairs.count(ch)) {
                if (stk.empty() || stk.top() != pairs[ch]) {
                    return false;
                }
                stk.pop();
            }
            else {
                stk.push(ch);
            }
        }
        return stk.empty();
    }
};

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值