Algorithm: valid-parentheses.

Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.

A valid string must meet:

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

Note that an empty string can be considered a valid string.

Example

Input: "()"
 Output: true

Example

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

Example

Input: "(]"
 Output: false

Example

Input: "([)]"
 Output: false

Example

Input: "{[]}"
 Output: true

Method: Stack

Judging the validity of parentheses can be solved by using the data structure "stack".

We traverse the given string s, and when we encounter an opening parenthesis, we expect that in the subsequent traversal, a closing parenthesis of the same type will close it. Since the left parenthesis encountered later must be closed first, we can put this left parenthesis on the top of the stack.

When we encounter a closing parenthesis, we need to close an opening parenthesis of the same type. At this point, we can take out the left parenthesis at the top of the stack and determine whether they are the same type of parenthesis. If it is not the same type, or there is no left parenthesis in the stack, the string s is invalid and False is returned. In order to quickly determine the type of parentheses, we can use HashMap to store each type of parentheses. The key of the hash map is the right parenthesis, and the value is the same type of left parenthesis.

After the traversal is over, if there is no left parenthesis in the stack, it means that we close all the left parentheses in the string ss and return True, otherwise return False.

Note that the length of a valid string must be an even number, so if the length of the string is an odd number, we can directly return False to save the subsequent traversal judgment process.

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();
    }
}

Complexity analysis

  • Time complexity: O(n), where n is the length of the string s.
  • Space complexity: O(n + ∣Σ∣), where Σ represents the character set. The string in this question only contains 6 kinds of brackets, ∣Σ∣=6. The number of characters in the stack is O(n), and the space used by the hash map is O(∣Σ∣), and the total space complexity can be obtained by adding them.

Guess you like

Origin blog.csdn.net/en_joker/article/details/108117143