leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法

本文介绍了一种使用栈数据结构来判断括号串是否有效的算法。该算法通过遍历输入字符串并利用栈进行匹配来确定括号是否正确闭合。文章提供了完整的Java代码实现。
Valid Parentheses 
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


思路:题目整体上比較明白,是对括号是否有效做推断,算法上是用栈来实现,单边入栈。配对之后出栈,最后推断栈是否为空。不为空说明最后没有配对完毕。返回false.

详细代码例如以下:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> st = new Stack<Character>();
        char[] ch = s.toCharArray();
        int len = ch.length;
        //假设长度为奇数,肯定无效
        if((len & 1) != 0){
            return false;
        }
        
        for(int i = 0; i < len; i++){
            if(st.isEmpty()){//栈为空,直接入栈
                st.push(ch[i]);
            }else{//不为空则讨论栈顶元素是否与ch[i]配对。

配对也出栈 if(isMatch(st.peek(),ch[i])){//是否配对 st.pop();//栈顶元素出栈 }else{ st.push(ch[i]);//不配对入栈 } } } return st.isEmpty(); } //a为栈顶元素,b为字符串最前元素 public static boolean isMatch(char a, char b){ switch(a){ case '(': if(b == ')') return true; else return false; case '{': if(b == '}') return true; else return false; case '[': if(b == ']') return true; else return false; default : return false; } } }



转载于:https://www.cnblogs.com/jzssuanfa/p/6890564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值