当前位置:网站首页>Leetcode20. Valid parentheses

Leetcode20. Valid parentheses

2022-07-05 12:54:00 accumulate steadily ض

Valid parenthesis  

 -->20. Valid parenthesis

This is also a classic problem of stack application

Input :s = "( )"          Output :true        Input :s = "( )[ ]{ }"        Output :true
Input :s = "( ]"          Output :false        Input :s = "( [ ) ]"          Output :false
Input :s = "{ [ ] }"        Output :true

There are three kinds of brackets in this question 【】{} () Then these three can be mixed or not , See if it matches ?

Ideas :

The left parentheses are stacked , Then check whether the traversal character matches it , If it matches, pop up the left bracket at the top of the stack and continue to traverse , If there are elements in the last stack , Or there is a string that has not been traversed, but the stack is empty, which is not matched

class Solution {
    public boolean isValid(String s) {
       // If it's a left bracket, put it on the stack 
       Stack<Character> stack = new Stack<>();
       for(int i =0;i<s.length();++i){
            // If it's a left bracket, put it on the stack 
            if(s.charAt(i)=='('||s.charAt(i)=='['
            ||s.charAt(i)=='{'){
                stack.push(s.charAt(i));
            }else {
                // If it's not the right parenthesis, compare it with the top element of the stack 
                if(stack.empty()){
                    // If the stack is empty , Can't compare 
                    return false;
                }else {
                    // The stack is not empty to see whether it is a match 
                    if((stack.peek()=='('&&s.charAt(i)==')')
                    ||(stack.peek()=='{'&&s.charAt(i)=='}')||
                    (stack.peek()=='['&&s.charAt(i)==']')){
                        stack.pop();
                    }else {
                        // If equal, pop up the top element 
                       return false;
                    }
                }
            }
       }
           return stack.empty();
    }
}

原网站

版权声明
本文为[accumulate steadily ض]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/07/202207051239247835.html