Given a string s containing just the characters (
, )
, {
, }
, [
and ]
, determine if the input string is valid.
An input string is valid if:
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
Input: s = "([)]"
Output: false
Input: s = "{[]}"
Output: true
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;
};
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;
};