Valid Parentheses

Problem

Given a string s 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.

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 ’()[]{}‘.

My Solution

success
const isValid = (s) => {
	const pair = {
		'(': 1,
		')': -1,
		'{': 2,
		'}': -2,
		'[': 3,
		']': -3,
	};
	if (s.length % 2 !== 0) return false;
	let checkNum = 0;
	let checkArr = [];
	for (symbol of s) {
		checkNum += pair[symbol];
		checkArr.push(pair[symbol]);
	}
	if (checkNum !== 0) return false;
	let halfCheck = [];
	const half = checkArr.length / 2;
	for (i = 0; i < half; i++) {
		if (checkArr[half - 1 - i] + checkArr[half + i] !== 0) {
			halfCheck = [...halfCheck, checkArr[half - 1 - i], checkArr[half + i]];
		}
	}
	if (halfCheck.length === 0) return true;
	const remainder = checkArr.filter(
		(el, idx) => el + checkArr[idx + 1] !== 0 && el + checkArr[idx - 1] !== 0
	);
	return remainder.length === 0;
};
success
const isValid = (s) => {
	if (s === null || s.length <= 0) return true;
	const cArr = s.split('');
	let stack = [];
	for (c of cArr) {
		if (c === '[') stack.push(']');
		else if (c === '{') stack.push('}');
		else if (c === '(') stack.push(')');
		else if (stack.length === 0 || c !== stack.pop()) return false;
	}
	if (stack.length === 0) return true;
	return false;
};