The task is taken from leetcode
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
My functional solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = s => {
const par = {
"(": ")",
"{": "}",
"[": "]",
};
const rep = [];
return [...s].every(x => par[x]
? rep.push(par[x])
: rep.pop() === x) && !rep.length;
};
My imperative soltion
/**
* @param {string} s
* @return {boolean}
*/
var isValid2 = s => {
const par = {
"(": ")",
"{": "}",
"[": "]",
};
const rep = [];
for (let i = 0; i < s.length; i++) {
if (par[s[i]]) {
rep.push(par[s[i]]);
} else {
if (rep.pop() !== s[i]) {
return false;
}
}
}
return rep.length === 0;
};