leetcode刷题Valid Parentheses

本文探讨了如何使用栈数据结构解决括号匹配问题,通过分析字符串中的括号类型,确保每种开括号都能被相应的闭括号正确关闭。文章提供了具体的代码实现,并强调了空字符串的有效性。

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

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

 

分析题目可以发现,这里面的数据都是有一定的对称性,有一种各自匹配消除的感觉,这里就想到了, 由于{},[]和()的ASSCII码的差值还不一样,前面两个是2,后面一个是1,这个要注意一下.

这道题目的主要目的是检测测试者对栈的数据结构的熟悉程度,这道题目用栈做很方便.直接上代码

if(s.empty())
               return true;
           int num = s.size();
           int mid = int(num / 2);
           if(num%2 !=0)
               return false;
           stack <int> all;
           for(int i=0;i<num;i++)
           {

                   if(!all.empty()&&((all.top()-s[i] == -1)||(all.top()-s[i]==-2)))
                   {
                       
                          all.pop();
                   }
                   else
                   {
                       all.push(s[i]);
                   }

           }

           if(all.empty())
              return true;
           else
               return false;
    }

note:  char可以强制转换成int型

note:在运用A&& B判断时,只要A不满足条件,条件B是不执行的,所以不用担心栈的pop会越界.这个小知识点很有用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白码思

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值