1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add valid-parentheses/javascript/function

This commit is contained in:
Théo LUDWIG 2024-11-18 01:19:24 +01:00
parent f28d1b816d
commit 9b925eea92
Signed by: theoludwig
GPG Key ID: ADFE5A563D718F3B
3 changed files with 48 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# valid-parentheses/javascript/function
Created by [@theoludwig](https://github.com/theoludwig) on 18 November 2024.

View File

@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@ -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
}