1. Title Description

Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective.

A valid string must meet the following requirements:

An open parenthesis must be closed with a close parenthesis of the same type. The left 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

Tip:

1 <= s.length <= 104

S consists only of parentheses ‘()[]{}’

Ii. Analysis of Ideas:

When I see the matching of parentheses, I think of the example of stack in the data structure class in college, which is used to realize the operation of addition, subtraction, multiplication and division with parentheses. The idea is consistent with the problem, so consider using the stack out of the stack and onto the stack to achieve.

Iii. AC Code:

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = bracketMap();
        char[] chars = s.toCharArray();
        if (chars.length%2! =0) {return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < chars.length; i++) {
            boolean flag = map.containsKey(chars[i]);
            if (flag){
                stack.add(chars[i]);
            }else {
                if (stack.empty()){
                    return false;
                }
                Character pop = stack.pop();
                if(chars[i] ! = map.get(pop)){return false; }}}return stack.empty();
    }

    public Map<Character,Character> bracketMap(a){
        Map<Character,Character> map = new HashMap<>();
        map.put('('.') ');
        map.put('{'.'} ');
        map.put('['.'] ');
        returnmap; }}Copy the code

Iv. Summary:

For extreme performance consider implementing your own simple stack completion.

“This article is participating in the” Gold Digging march Campaign “, click to see the details of the campaign.”