LeetCode-20: valid brackets

Original title:

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

A valid string must meet:

The left bracket must be closed with the same type of right bracket.
The left bracket must be closed in the correct order.
Note that an empty string can be considered a valid string.

Problem-solving ideas:

Through observation, it can be found that the effective parentheses have at least a group of left and right brackets adjacent to each other, and then the substring composed of adjacent left and right brackets can be removed to judge the validity of the remaining parts. (This is like calculating a math problem by yourself. Generally, the deepest parenthesis is calculated first, and then the parentheses of the next layer are calculated until the last layer). The specific solution ideas are as follows:

1. Construct the mapping between the right and left brackets;

2. Build a stack, traverse the string, encounter the left bracket and place it on the stack, and the right bracket, according to the mapping relationship in step 1, determine whether the bracket on the top of the stack and the right bracket constitute a valid bracket, if not Composition, directly return false. If it is valid, pop the top element of the stack and continue traversing; (the stack data structure is last in first out, so the stack is used to store the traversed bracket characters)

3. Determine whether the final stack is empty. If it is not empty, it is not a valid bracket.

answer:

 1 class Solution {
 2     public static boolean isValid(String s) {
 3         HashMap<Character , Character> maps = new HashMap<>();
 4         int len = s.length();
 5         if(len % 2 != 0) return false; //长度为奇数,直接返回false
 6         maps.put(')', '(');
 7         maps.put('}', '{');
 8         maps.put(']', '[');
 9         Stack<Character> stack = new Stack<Character>();
10         for (int i = 0; i < s.length(); i++) {
11             char c = s.charAt(i);
12             if (maps.containsKey(c)) {
13                 char topElement = stack.empty() ? '#' : stack.pop();
14                 if (topElement != maps.get(c)) {
15                     return false;
16                 }
17             } else {
18                 stack.push(c);
19             }
20         }
21         return stack.isEmpty();
22     }
23 }

 

Guess you like

Origin www.cnblogs.com/zhang-yi/p/12757783.html