LeeCode20 valid parentheses (Java) (stack)

Title link: LeeCode20 valid parentheses
Title description:
Insert picture description here
Use the stack to store the left parenthesis and see the right parenthesis to determine if it is the innermost parenthesis

class Solution {
    
    
    public  boolean isValid(String s) {
    
    
        boolean ans=true;
        Stack<Character> stack=new Stack<>();
        for (int i = 0; i < s.length(); i++) {
    
    
            if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
    
    
                stack.add(s.charAt(i));
            }else{
    
    
            	//还没有左括号就直接进右括号直接错
                if(stack.empty())return false;
                if(s.charAt(i)==')'&&stack.pop()!='(') ans=false;
                if(s.charAt(i)==']'&&stack.pop()!='[') ans=false;
                if(s.charAt(i)=='}'&&stack.pop()!='{') ans=false;
            }
        }
        if(!stack.empty()){
    
    
            ans=false;
        }return ans;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/112470867