From 9b925eea920b7fbca9b827bf81f7801d6e4a62ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20LUDWIG?= Date: Mon, 18 Nov 2024 01:19:24 +0100 Subject: [PATCH] feat(solutions): add `valid-parentheses/javascript/function` --- .../solutions/javascript/function/README.md | 3 ++ .../javascript/function/package.json | 3 ++ .../solutions/javascript/function/solution.js | 42 +++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 challenges/valid-parentheses/solutions/javascript/function/README.md create mode 100644 challenges/valid-parentheses/solutions/javascript/function/package.json create mode 100644 challenges/valid-parentheses/solutions/javascript/function/solution.js diff --git a/challenges/valid-parentheses/solutions/javascript/function/README.md b/challenges/valid-parentheses/solutions/javascript/function/README.md new file mode 100644 index 0000000..fb8b405 --- /dev/null +++ b/challenges/valid-parentheses/solutions/javascript/function/README.md @@ -0,0 +1,3 @@ +# valid-parentheses/javascript/function + +Created by [@theoludwig](https://github.com/theoludwig) on 18 November 2024. diff --git a/challenges/valid-parentheses/solutions/javascript/function/package.json b/challenges/valid-parentheses/solutions/javascript/function/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/challenges/valid-parentheses/solutions/javascript/function/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/challenges/valid-parentheses/solutions/javascript/function/solution.js b/challenges/valid-parentheses/solutions/javascript/function/solution.js new file mode 100644 index 0000000..a55074d --- /dev/null +++ b/challenges/valid-parentheses/solutions/javascript/function/solution.js @@ -0,0 +1,42 @@ +import readline from "node:readline" + +const input = [] +const readlineInterface = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}) +readlineInterface.on("line", (value) => { + input.push(value) +}) +readlineInterface.on("close", solution) + +function solution() { + console.log(isValidParentheses(input[0])) +} + +const mapCloseOpen = { + ")": "(", + "]": "[", + "}": "{", +} +const closeCharacters = Object.keys(mapCloseOpen) +const openCharacters = Object.values(mapCloseOpen) + +/** + * @param {string} string + * @return {boolean} + */ +const isValidParentheses = (string) => { + const stack = [] + for (let index = 0; index < string.length; index++) { + if (openCharacters.includes(string[index])) { + stack.push(string[index]) + } else if (closeCharacters.includes(string[index])) { + const last = stack.pop() + if (last !== mapCloseOpen[string[index]]) { + return false + } + } + } + return stack.length <= 0 +}