Algorithm: Match valid parentheses 20. Valid Parentheses

For the complete collection of LeetCode, please refer to: LeetCode Github Collection

topic

20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets 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

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

Stack solution

Match the left and right parentheses, use the stack to solve,

  1. When the left parenthesis is put on the stack;
  2. When the right parenthesis is popped, it is judged whether the left parenthesis is the same type. If the stack is empty or does not match, it returns false;
  3. After the end, if the Stack stack is empty, it matches true.
class Solution {
    
    
    public boolean isValid(String s) {
    
    
        // check edge
        if (s == null || s.length() == 0) {
    
    
            return true;
        }
        
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> map = new HashMap<>();
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');
        
        char[] chars = s.toCharArray();
        for(char c: chars) {
    
    
            if (c == '(' || c == '{' || c == '[') {
    
    
                stack.push(c);
                continue;
            }
            
            if (stack.isEmpty() || stack.pop() != map.get(c)) return false;
        }
        
        return stack.isEmpty();
    }
}

Guess you like

Origin blog.csdn.net/zgpeace/article/details/113059486