diff --git a/leetcode/20 - validparenthesis/valid-parenthesis.js b/leetcode/20 - validparenthesis/valid-parenthesis.js new file mode 100644 index 0000000..b41f838 --- /dev/null +++ b/leetcode/20 - validparenthesis/valid-parenthesis.js @@ -0,0 +1,36 @@ +var isValid = function (s) { + var stack = []; + var dict = []; + + dict.push({ key: "(", value: ")" }); + dict.push({ key: "[", value: "]" }); + dict.push({ key: "{", value: "}" }); + + const found = dict.find(element => element.key === '('); + + for (const character of s) { + switch (character) { + case '(': + case '[': + case '{': + stack.push(dict.find(element => element.key === character)); + break; + case ')': + case ']': + case '}': + const foundCharacter = dict.find(element => element.value === character); + if (stack.length === 0 || stack[stack.length - 1] != foundCharacter) { + return false; + } + + stack.pop(); + break; + } + } + + return stack.length === 0; + +}; + +console.log(isValid('()[]{}')); // true +console.log(isValid('([)]')); // false \ No newline at end of file