-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalid-parentheses.js
More file actions
34 lines (29 loc) · 940 Bytes
/
valid-parentheses.js
File metadata and controls
34 lines (29 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// https://leetcode.com/problems/valid-parentheses/
// Related Topics: String, Stack
// Difficulty: Easy
/*
Initial thoughts:
Creating a lookup table for all the types of parentheses and
using a stack we touch every element of the input string and
if it's an opening parenthes push it on the stack and if its
a closing parenthes we pop one from the stack checking if it's
a valid counterpart for the current parenthes.
At the end, the stack must be empty
Time complexity: O(n) where n === s.length
Space complexity: O(n) where n === s.length
*/
/**
* @param {string} s
* @return {boolean}
*/
const isValid = s => {
const stack = [];
for (let i = 0; i < s.length; i++) {
const temp = s[i];
if (opening[temp]) stack.push(temp);
else if (stack.pop() !== closing[temp]) return false;
}
return stack.length === 0;
};
const opening = { '(': ')', '[': ']', '{': '}' };
const closing = { ')': '(', ']': '[', '}': '{' };