leetcode--demo20有效的括号

leetcode–demo20有效的括号

这题考的就是数据结构中栈的使用,此外就是括号匹配的问题,其他的也没啥了。

import java.util.Stack;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(new Solution().isValid("([)]"));
    }
}
class Solution {
    
    
    public boolean isValid(String s) {
    
    
        //创建一个栈
        Stack<Character> stack = new Stack<>();
        for (int i=0;i<s.length();i++){
    
    
            if (stack.size()!=0&&check(stack.peek(),s.charAt(i))){
    
    
                stack.push(s.charAt(i));
                stack.pop();
                stack.pop();
            }else {
    
    
                stack.push(s.charAt(i));
            }
        }
        if (stack.size()==0){
    
    
            return true;
        }else {
    
    
            return false;
        }
    }
    //需要一个方法去判断括号是否匹配
    public boolean check(char a,char b){
    
    
        if (a=='('&&b==')'){
    
    
            return true;
        }else if (a=='['&&b==']'){
    
    
            return true;
        }else if (a=='{'&&b=='}'){
    
    
            return true;
        }else {
    
    
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_48126147/article/details/113115260
今日推荐