LeetCode - Valid Parentheses

1 minute read

Problem description

description

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

1
2
Input: "()"
Output: true

Example 2:

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

Example 3:

1
2
Input: "(]"
Output: false

Example 4:

1
2
Input: "([)]"
Output: false

Example 5:

1
2
Input: "{[]}"
Output: true

Analysis

This is a easy question and use stack is the easiest way to solve it.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ValidParentheses {
  public boolean isValid(String s) {
    List<Character> stack = new ArrayList<>();

    for (char c : s.toCharArray()) {
      if (c == ')') {
        if (stack.isEmpty() || stack.remove(stack.size() - 1) != '(') {
          return false;
        }
      } else if (c == ']') {
        if (stack.isEmpty() || stack.remove(stack.size() - 1) != '[') {
          return false;
        }
      } else if (c == '}') {
        if (stack.isEmpty() || stack.remove(stack.size() - 1) != '{') {
          return false;
        }
      } else {
        stack.add(c);
      }
    }

    return stack.size() == 0;
  }
}

What to improve

  • must be careful about the index out of bound exception, should check index range before every operation of array.