LeetCode——020

本文介绍了一个简单的算法问题——括号匹配验证。通过使用栈数据结构,该算法能够判断字符串中的括号是否正确配对。文章详细解释了实现过程及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述
/*
20. Valid Parentheses My Submissions QuestionEditorial Solution
Total Accepted: 103991 Total Submissions: 355405 Difficulty: Easy
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

Subscribe to see which companies asked this question
*/
/*
解题思路:
这题就是栈的基本应用。
策略只有一点:遇到左括号入,遇到右括号出并比较。

注意点:在返回的时候如果正确应该栈为空,所以返回的是栈的空判断。
*/

class Solution {
public:
    bool isValid(string s) {

        //此题是栈的基本应用的一个实例
        stack<char> _stack;
        if(s.empty())return true;

        for(int i=0;i<s.size();i++){
            char c=s[i];
            //若果是左元素就入栈
            if(c=='('||c=='['||c=='{'){
                _stack.push(c);
            }else{
                //在取之前先判断是否为空
                if(_stack.empty())return false;

                int tmp=_stack.top();
                _stack.pop();
                switch(c){
                    case ')': if(tmp!='(') return false;break;
                    case ']': if(tmp!='[') return false;break;
                    case '}': if(tmp!='{') return false;break;
                }
            }

        }
        return _stack.empty();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值