Valid Parentheses

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution:

  1. public class Solution {
  2. public boolean isValid(String s) {
  3. char[] p = "(){}[]".toCharArray();
  4. Map<Character, Character> map = new HashMap<>();
  5. for (int i = 0; i < p.length - 1; i += 2)
  6. map.put(p[i + 1], p[i]);
  7. Stack<Character> stack = new Stack<>();
  8. for (char c : s.toCharArray()) {
  9. if (c == '(' || c == '{' || c == '[')
  10. stack.push(c);
  11. else if (stack.isEmpty() || stack.peek() != map.get(c))
  12. return false;
  13. else
  14. stack.pop();
  15. }
  16. return stack.isEmpty();
  17. }
  18. }