LeetCode知识点总结 - 20

该博客介绍了如何通过栈数据结构解决LeetCode中的第20题——有效括号。主要思路是遇到开括号就压入栈,遇到闭括号时检查与栈顶括号是否匹配,不匹配则返回false。最后检查栈是否为空,不空则返回false,否则返回true。此方法重点在于理解栈的特性并应用到字符串匹配中。
摘要由CSDN通过智能技术生成

LeetCode 20. Valid Parentheses

考点难度
StringEasy
题目

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.

思路

用stack,如果是前半个括号就push到stack里,后半个括号检查和pop出来的括号是不是匹配,如果不匹配返回false。最后检查stack里有没有多余的括号,有的话返回false

答案
class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            char a = s.charAt(i);
            if(a == '(' || a == '[' || a == '{') {
                st.push(a);
            }
            else if(st.empty()) {
                return false;
            }
            else if(a == ')' && st.pop() != '(') {
                return false;
            }
            else if(a == ']' && st.pop() != '[') {
                return false;
            }
            else if(a == '}' && st.pop() != '{') {
                return false;
            }
        }
        return st.empty();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值