Niuke Net Brushing Questions-Bracket Sequence

Problem Description

Given a string containing only the characters'(',')','{',')','[' and']', determine whether the given string is a legal bracket sequence. The
brackets must be correct The order is closed, "()" and "()[]{}" are both legal bracket sequences, but "(]" and "([)]" are illegal.

Input description:
input a string in parentheses

Output description:
output whether this bracket is legal

Example

Example 1

Enter
"[]"

Output
true

Solutions

analysis

  1. With the help of the stack data structure, you can encounter the left parenthesis such as the stack, and the right parenthesis pops the stack

method

  1. With the help of the stack data structure, you can encounter the left parenthesis such as the stack, and the right parenthesis pops out of the stack.
    (PS Tips: You can encounter the left parenthesis, and the right parenthesis into the stack, which can save space)

Code

// 思路1
public class Solution {
    
      
    public boolean isValid (String s) {
    
    
        if (s == null || s.length() == 0 || "".equals(s)) {
    
    
            return true;
        }
        // write code here

        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));
                continue;
            }

            if (stack.isEmpty()) return false;

            if (s.charAt(i) == ')' && stack.pop() == '(') {
    
    
                continue;
            } else if (s.charAt(i) == ']' && stack.pop() == '[') {
    
    
                continue;
            } else if (s.charAt(i) == '}' && stack.pop() == '{') {
    
    
                continue;
            } else {
    
    
                return false;
            }
        }

        return stack.isEmpty();
    }

	// 小技巧
    public boolean isValid2(String s) {
    
    
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
    
    
            if (c == '(')
                stack.push(')');
            else if (c == '[')
                stack.push(']');
            else if (c == '{')
                stack.push('}');
            else if (stack.empty() || stack.pop() != c)
                return false;
        }
        return stack.empty();
    }
}

Time complexity analysis:
O(N): The number of times to traverse the string is N, so the time complexity is O(N)

Space complexity analysis:
O(N): Assuming that all strings are left parentheses, all strings need to be pushed onto the stack, so the space complexity is O(N)

If you want to test, you can go directly to the link of Niuke.com to do the test

Bracket sequence-niuke.com

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113683730