Leetcode-020-valid parentheses

Time:2022-1-23

Valid parentheses

Title Description: give a string s that only includes’ (‘,’ ”, ‘{‘, ‘}’, ‘[‘, ‘]’, and judge whether the string is valid.

Valid strings must meet:

The left parenthesis must be closed with the same type of right parenthesis.
The left parentheses must be closed in the correct order.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Solution 1: using stack

Initializes an open bracket stackleftParentheses, traversal stringsFor each character of the, when an open bracket is encountered, the current character isPush , when the closing bracket is encountered, judgeleftParenthesesWhether the character at the top of the stack is the left bracket corresponding to the current character. If not, the return is invalid; otherwiseOut of stack。 After traversal, judgeIs leftparentheses empty, if it is not empty, it means that there is no corresponding right bracket in the left bracket, and the return is invalid; Otherwise, it is valid.

import java.util.Stack;

public class Solution {
    public static boolean isValid(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        Stack<Character> leftParentheses = new Stack<>();
        for (char parentheses : s.toCharArray()) {
            if (parentheses == '(' || parentheses == '{' || parentheses == '[') {
                leftParentheses.push(parentheses);
            } else if (parentheses == ')') {
                if (leftParentheses.size() > 0 && leftParentheses.peek() == '(') {
                    leftParentheses.pop();
                } else {
                    return false;
                }
            } else if (parentheses == ']') {
                if (leftParentheses.size() > 0 && leftParentheses.peek() == '[') {
                    leftParentheses.pop();
                } else {
                    return false;
                }
            } else if (parentheses == '}') {
                if (leftParentheses.size() > 0 && leftParentheses.peek() == '{') {
                    leftParentheses.pop();
                } else {
                    return false;
                }
            }
        }
        if (leftParentheses.size() != 0) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isValid("()[]{}"));
    }
}

[daily message]Every morning after waking up is a gift. Take every happy smile as a habit. A beautiful day starts from now on.