diff --git a/leetcode/solutions/0020.ValidParentheses/isValid.ts b/leetcode/solutions/0020.ValidParentheses/isValid.ts new file mode 100644 index 0000000..44360ea --- /dev/null +++ b/leetcode/solutions/0020.ValidParentheses/isValid.ts @@ -0,0 +1,23 @@ +/** + * @param {string} s + * @return {boolean} + */ +export default function isValid( + s: string +): boolean { + if (s.length % 2 !== 0) { + return false; + } + + const closerMap = new Map([["{", "}"], ["(", ")"], ["[", "]"]]); + const openerSet = new Set(closerMap.keys()); + const closerStack: string[] = []; + for (let i = 0; i < s.length; i++) { + if (openerSet.has(s[i])) { + closerStack.push(closerMap.get(s[i])!); + } else if (closerStack.pop() !== s[i]) { + return false; + } + } + return closerStack.length === 0; +} diff --git a/leetcode/solutions/0020.ValidParentheses/isValid_test.ts b/leetcode/solutions/0020.ValidParentheses/isValid_test.ts new file mode 100644 index 0000000..1107fed --- /dev/null +++ b/leetcode/solutions/0020.ValidParentheses/isValid_test.ts @@ -0,0 +1,11 @@ +import { test } from "https://deno.land/std/testing/mod.ts"; +import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; +import isValid from "./isValid.ts"; + +test("0020. Valid Parentheses", () => { + assertEquals(isValid("()"), true); + assertEquals(isValid("()[]{}"), true); + assertEquals(isValid("(]"), false); + assertEquals(isValid("([)]"), false); + assertEquals(isValid("{[]}"), true); +});