20. Valid Parentheses

该问题要求使用栈数据结构配合哈希映射检查给定的括号字符串是否有效,确保括号正确配对且顺序无误。程序遍历字符串,遇到开括号入栈,遇到闭括号则检查栈顶元素是否为其对应开括号,若不匹配或栈为空则返回无效。遍历结束后栈为空则表示有效,否则无效。
摘要由CSDN通过智能技术生成

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = “()”
Output: true
Example 2:

Input: s = “()[]{}”
Output: true
Example 3:

Input: s = “(]”
Output: false

Constraints:

1 <= s.length <= 104
s consists of parentheses only ‘()[]{}’.

Solution1 Stack

  • Maintain a stack s ,and maintain a hash map m like this:
    {
    {“{”, “}”},
    {“[”,“]”},
    {“(”,“)”}
    }

  • if the size of the string is an odd number then return false;

  • Loop over the string,

  • if the current character is an open bracket, then push it into s

  • if it is a close bracket, then get the top element of s, denoted as variable p, if m.at(p) does not equal the current character then return false, otherwise

  • Pop the top of the stack。 if s is empty after the looping is done then return true, otherwise return false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值