[Algorithm -- LeetCode] (020) Effective parentheses

insert image description here

1. Topic

Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

  1. An opening parenthesis must be closed with a closing parenthesis of the same type.
  2. Opening parentheses must be closed in the correct order.
  3. Each closing parenthesis has a corresponding opening parenthesis of the same type.

Example 1:

Input : s = "()"
Output : true

Example 2:

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

Example 3:

Input : s = "(]"
Output : false

Link to the topic: https://leetcode.cn/problems/valid-parentheses

2. Diagram

Verify the symmetry of the brackets. The brackets are divided into three types: small brackets, square brackets and curly brackets. You can use the first-in-last-out feature of the stack to put all the left brackets ["(", "[", "{"] into the stack first, and then when you encounter a right bracket, let it match with the element on the top of the stack. Whether "(([]))" is legal, the execution process is as follows:

  • When the left parenthesis is encountered first, it is pushed onto the stack first:
    insert image description here

  • 接下来又是左括号,继续入栈:
    insert image description here
    然后又是左中括号,继续入栈:
    insert image description here
    接下来是右中括号,与栈顶元素匹配,“[]”为一对合法的括号,匹配成功栈顶元素出栈:
    insert image description here
    接下来又是右括号,与栈顶元素匹配,“()”为一对合法的括号,匹配成功栈顶元素出栈:
    insert image description here
    接下来又是右括号,与栈顶元素匹配,“()”为一对合法的括号,匹配成功栈顶元素出栈:
    insert image description here
    当字符串循环结束并且栈为空栈时,则证明此字符串的括号匹配合法,最终的效果如下图所示:
    insert image description here

3. Java sample code

class Solution {
    
    
    public boolean isValid(String s) {
    
    
    //1.特判
    if (s.isEmpty()) return true;
    //2.创建辅助栈
    Stack<Character> stack = new Stack<>();
    //3.遍历
    for (char c : s.toCharArray()) {
    
    
        if (c == '(') {
    
    
            stack.push(')');
        } else if (c == '[') {
    
    
            stack.push(']');
        } else if (c == '{') {
    
    
            stack.push('}');
        } else if (stack.isEmpty() || c != stack.pop()) {
    
    
            return false;
        }
    }
    //4.返回
    return stack.isEmpty();
    }
}

Results of the:
insert image description here

Guess you like

Origin blog.csdn.net/duoduo_11011/article/details/131678276