赵二的刷题日记034《有效的括号》

该博客主要讨论如何实现一个有效的括号字符串检查算法。通过使用栈数据结构,当遇到左括号时将其压栈,遇到右括号时检查是否与栈顶的左括号匹配,若不匹配或栈为空则返回false。遍历字符串结束后,栈内仍有元素则返回false,否则返回true。此算法可应用于编程语言解析和编译器设计等领域。
摘要由CSDN通过智能技术生成

Valid Parentheses

Given a string s 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.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

class Solution {
    public boolean isValid(String s) {
        //扫描到左括号就压栈,扫描到右括号就弹栈,如果不匹配,返回false
        //如果扫描结束后,栈内还有东西,返回false
        //结束后栈空了,返回true
        //扫描到右括号时,栈空,返回false
        
        
        Stack<Character> res = new Stack<>();
        char[] str = s.toCharArray();
        
        for (int i = 0; i < str.length; i++) {
            if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
                res.push(str[i]);
            }
            
            if (str[i] == ')') {
                if (res.isEmpty()) {
                    return false;
                }
                
                char c = res.pop();
                if (c != '('){
                    return false;
                }
            }
            
            if (str[i] == ']') {
                if (res.isEmpty()) {
                    return false;
                }
                
                char c = res.pop();
                if (c != '['){
                    return false;
                }
            }
            
            if (str[i] == '}') {
                if (res.isEmpty()) {
                    return false;
                }
                
                char c = res.pop();
                if (c != '{'){
                    return false;
                }
            }
        }//扫描结束
        
        if (!res.isEmpty()) {
            return false;
        }
        
        
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值