diff --git a/leetcode/20 - validparenthesis/valid-parenthesis.js b/leetcode/20 - validparenthesis/valid-parenthesis.js new file mode 100644 index 0000000..5aec27c --- /dev/null +++ b/leetcode/20 - validparenthesis/valid-parenthesis.js @@ -0,0 +1,26 @@ +const OBJECT_MAPPING = { + ')': '(', + ']': '[', + '}': '{', +} + +var isValid = function (s) { + const opens = [] + for (c of s) { + if (c === '(' || c === '[' || c === '{') { + opens.push(c) + } else { + if (opens.length === 0) { + return false; + } + const lastOpen = opens[opens.length - 1]; + if (OBJECT_MAPPING[c] != lastOpen) { + return false + } else { + opens.pop(); + } + } + } + + return opens.length === 0 +}; \ No newline at end of file