LeetCode Day 4 20. Effective Parentheses

The LeetCode 100-day foundation building series is mainly for practicing basic data structures and algorithms. The question bank is all LeetCode simple questions (medium and difficult questions will be updated in other series later), mainly written in C language and Java, and the previous questions can be completed. For the purpose of function, better algorithms and optimized code blocks will be used later.
20. Valid Parentheses

Given a string s consisting only of '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string needs to satisfy:
the opening parenthesis must be closed with the same type of closing parenthesis.
Opening parentheses must be closed in the correct order.
Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-parentheses
C language:

char pairs(char a) {
    
    
    if (a == '}') return '{';
    if (a == ']') return '[';
    if (a == ')') return '(';
    return 0;
}
bool isValid(char* s) {
    
    
    int n = strlen(s);
    if (n % 2 == 1) {
    
    
        return false;
    }
    int stack[n + 1], top = 0;
    for (int i = 0; i < n; i++) {
    
    
        char ch = pairs(s[i]);
        if (ch) {
    
    
            if (top == 0 || stack[top - 1] != ch) {
    
    
                return false;
            }
            top--;
        } else {
    
    
            stack[top++] = s[i];
        }
    }
    return top == 0;
}

Problem-solving idea: The length of the effective bracket string must be an even number. Before the closing parenthesis, there must be a corresponding opening parenthesis in order to offset. If the right parenthesis is not the corresponding left parenthesis, then the string must not be a valid parenthesis. Then, if a left parenthesis is encountered, it will be pushed onto the stack, and if a right parenthesis is encountered, the top of the stack will be popped, and if the two correspond, they will be offset. If the popped top of the stack such as "{" and "{" are not corresponding, return false.
Java:

class Solution {
    
    
    public boolean isValid(String s) {
    
    
        int n = s.length();
        if (n % 2 == 1) {
    
    
            return false;
        }

        Map<Character, Character> pairs = new HashMap<Character, Character>() {
    
    {
    
    
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
    
    
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)) {
    
    
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
    
    
                    return false;
                }
                stack.pop();
            } else {
    
    
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}

IsValid()
checks whether the object variable has been instantiated, that is, whether the value of the instance variable is a valid object.
Syntax IsValid ( objectname )
Parameter objectname Object name to be detected
Return value is Boolean. If the specified object has created an instance of the case, then the IsValid() function returns True, otherwise it returns FALSE. If the value of the parameter obejctname is NULL, the IsValid() function returns NULL.

isEmpty()
is a function to judge whether the array A is empty.
Usage: C = isempty(A):
If A is empty, the returned value is 1
If A is non-empty, the returned value is 0

pop and peek:
peek and pop both return the top element of the stack;
the peek() function returns the top element of the stack, but does not pop the top element of the stack; the
pop() function returns the top element of the stack, and pops the top element out of the stack

add and push:
both add and push can add elements to the stack;
add is a method inherited from Vector, and the return value type is boolean;
push is a method of Stack itself, and the return value type is the parameter class type;

The containsKey() method determines whether the specified key name is included.
containsKey() is often used in HashMap to determine whether the key (key) exists.

Guess you like

Origin blog.csdn.net/qq_43310387/article/details/123963138