From 1f9f36444f633df6803fed1107e285ffb340a2ad Mon Sep 17 00:00:00 2001 From: Leandro Oliveira Date: Fri, 22 Oct 2021 15:52:49 -0300 Subject: [PATCH] feat: add valid-parenthesis challenge in js --- .../valid-parenthesis.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 leetcode/20 - validparenthesis/valid-parenthesis.js 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