-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidParentheses.js
More file actions
executable file
·45 lines (34 loc) · 1.13 KB
/
validParentheses.js
File metadata and controls
executable file
·45 lines (34 loc) · 1.13 KB
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
35
36
37
38
39
40
41
42
43
44
45
// function to validate parentheses
// what is valid parentheses?
// 1. Open parentheses must be closed by the same type of parentheses.
// 2. Open parentheses must be closed in the correct order.
// 3. An empty string is also considered valid.
function isValid(s) {
const stack = [];
const map = {
'(': ')',
'{': '}',
'[': ']'
};
for (let char of s) {
if (map[char]) {
// If it's an opening bracket, push the corresponding closing bracket onto the stack
stack.push(map[char]);
} else {
// If it's a closing bracket, check if it matches the top of the stack
if (stack.pop() !== char) {
return false;
}
}
}
// If the stack is empty, all brackets were matched correctly
return stack.length === 0;
}
// time complexity: O(n)
// space complexity: O(n)
// test the function
console.log(isValid("()")); // Output: true
console.log(isValid("()[]{}")); // Output: true
console.log(isValid("(]")); // Output: false
console.log(isValid("([)]")); // Output: false
console.log(isValid("{[]}")); // Output: true