-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidParenthesis.js
27 lines (24 loc) · 947 Bytes
/
validParenthesis.js
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
function isValidParentheses(s) {
const stack = []; // Using an array as a stack
const openingSet = new Set(['(', '{', '[']); // Set to check for opening parentheses
const parenthesesMap = {
')': '(',
'}': '{',
']': '[',
};
for (const char of s) {
if (openingSet.has(char)) {
// If the character is an opening parenthesis, push it onto the stack
stack.push(char);
} else {
// If the character is a closing parenthesis
const lastOpened = stack.pop(); // Pop the top element from the stack
// Check if the popped opening parenthesis matches the expected opening parenthesis
if (parenthesesMap[char] !== lastOpened) {
return false; // Mismatched parentheses
}
}
}
// The string is valid if the stack is empty (all parentheses are matched)
return stack.length === 0;
}