Given a string s containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid. A valid string must satisfy: the opening parenthesis must be closed with a closing parenthesis of the same type. 【LeetCode Hot 100】

Question 20 of the Hottest Questions 100:

 Paste the code first:

class Solution {
    public boolean isValid(String s) {
        //新建栈,用以存储左括号
        Stack<Character> stack = new Stack<>();

        //for循环遍历字符串s,遇到左括号入栈,遇到右括号出栈,判断两个括号是否匹配
        for(int i = 0;i < s.length();i++){
            char ch = s.charAt(i);
            //若字符char为左括号,则入栈
            if(ch == '(' || ch == '[' || ch == '{'){
                stack.push(ch);
            }else{  //若为右括号,则开始判断
                if(!stack.isEmpty()){   //当栈不为空时,弹出栈顶元素,看看两个括号是否匹配
                    char outbrackets = stack.pop();
                    if( !func(outbrackets,ch) ){    //若不匹配则返回false
                        return false;
                    }
                }else{  //当栈为空时,说明在这个右括号前面没有左括号,不符合题意,返回false
                    return false;
                }
            }
        }

        //当for循环遍历完后,若栈中不为空,说明还剩下多余的左括号,同样不符合题意,返回false
        if(!stack.isEmpty()){
            return false;
        }
        return true;
    }
    //func函数用于判断两个括号是否匹配
    public boolean func(char a,char b){
        if(a == '(' && b == ')'){
            return true;
        }else if(a == '[' && b == ']'){
            return true;
        }else if(a == '{' && b == '}'){
            return true;
        }
        return false;
    }
}

Problem-solving ideas: We can solve this problem with the help of stacks. First of all we need to know under what circumstances this string s with only parentheses is valid?

That is, the left bracket "(" corresponds to the right bracket ")", the left bracket "[" corresponds to the right bracket "]", and the left bracket "{" corresponds to the right bracket "}". And the left and right parentheses need to be closed in the correct order. Let's look at a few counter-examples:

 Through the above figure, we understand what "invalid parentheses" are, so how to use stacks to solve this problem?

Since the storage feature of the stack is first-in-last-out, we can store each left parenthesis into the stack when traversing the string. When we encounter a right parenthesis, we can put the left parenthesis at the top of the stack (the last left parenthesis traversed to the stack). ) to pop the stack to see if the two parentheses match "valid", because if a closing parenthesis is encountered, it should always be closed by the nearest left parenthesis.

 

Guess you like

Origin blog.csdn.net/weixin_56960711/article/details/123277699