leetcode 20. Valid Parentheses(有效括号)

该博客主要讨论了如何检查输入字符串中的括号是否匹配,这是一个典型的栈应用问题。通过遍历字符串,遇到开括号则压栈,遇到闭括号则检查栈顶元素是否与之匹配并出栈。提供了三种不同的实现方式:使用HashMap和Stack、仅使用Stack以及使用数组模拟栈,所有方法都确保了正确性和效率。

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

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.

Example 1:

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

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

括号是否匹配的问题。而且字符串s中只有括号,没有其他字符。

思路:
典型的stack问题。
遇到"(", “[”, "{“压栈,遇到“)” “]”, "}"就看栈顶是不是与之对应的括号,出栈,如果这时栈为空或者不匹配,返回false。
最后如果栈为空,说明完全匹配,返回true。

    public boolean isValid(String s) {
        if(s.length() < 2) return false;
        HashMap<Character, Character> map = new HashMap<>();
        Stack<Character> stack = new Stack<>();
        
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        
        for(int i = 0; i < s.length(); i ++) {
            char ch = s.charAt(i);
            if(map.containsKey(ch)) {
                stack.push(ch);
            } else {
                if(stack.isEmpty() || 
                   ch != map.get(stack.pop())) return false;
            }
        }
        
        return (stack.isEmpty());
    }

也可以不用map,直接比较各括号,但是会慢一点

    public boolean isValid(String s) {
        if(s.length() < 2) return false;
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length(); i ++) {
            char ch = s.charAt(i);
            if(ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if(stack.isEmpty()) return false;
                char pair = stack.pop();
                if((ch == ')' && pair != '(') || 
                   (ch == ']' && pair != '[') ||
                    (ch == '}' && pair != '{')) return false;
            }
        }
        
        return (stack.isEmpty());
    }

用数组模拟栈会很高效。

    public boolean isValid(String s) {
        int n = s.length();
        int[] st = new int[n];

        int head = -1;

        for(int i = 0; i < n; i++) {
            if(head == -1) {
                st[++head] = s.charAt(i); //if stack.isEmpty(){stack.add(ch)}
                continue;
            }
            char ch = s.charAt(i);
            if(ch == ')') {
                if(st[head] != '(') return false;
                head--;
            } else if(ch == ']') {
                if(st[head] != '[') return false;
                head--;
            } else if(ch == '}') {
                if(st[head] != '{') return false;
                head--;
            } else {
                st[++head] = ch;
            }
        }
        return (head == -1);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值