Question:

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. Input: "()"
  2. Output: true
  3. Input: "()[]{}"
  4. Output: true
  5. Input: "(]"
  6. Output: false
  7. Input: "([)]"
  8. Output: false
  9. Input: "{[]}"
  10. Output: true

Solution:

  1. /**
  2. * @param {string} s
  3. * @return {boolean}
  4. */
  5. var isValid = function(s) {
  6. const error = [];
  7. const map = {
  8. ')': '(',
  9. '}': '{',
  10. ']': '['
  11. };
  12. const arr = s.split('');
  13. for (let i = 0; i < arr.length; i++) {
  14. if (error && map[arr[i]] && map[arr[i]] == error[error.length-1]) {
  15. error.pop();
  16. }else{
  17. error.push(arr[i]);
  18. }
  19. }
  20. return error.length === 0
  21. };

Runtime: 52 ms, faster than 99.86% of JavaScript online submissions for Valid Parentheses.