-
Notifications
You must be signed in to change notification settings - Fork 2
/
task5.js
52 lines (45 loc) · 1.66 KB
/
task5.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Day 21 - LeetCode Easy
*
* Activity 5: Merge Two Sorted Lists
* - Task 5: Solve the "Valid Parentheses" problem on LeetCode.
* - Write a function that takes a string containing just the characters '(', ')', '{', '}', '[' and ']', and determines if the input string is valid.
* - A string is valid if open brackets are closed in the correct order.
* - Log the result for a few test cases.
*/
// Function to check if a string of parentheses is valid
const isValid = (s) => {
// Create a stack to store the opening parentheses
const stack = [];
// Create a map to store the matching parentheses
const map = {
'(': ')',
'[': ']',
'{': '}'
};
// Loop through each character in the string
for (let char of s) {
// Check if the character is an opening parenthesis
if (map[char]) {
// Push the opening parenthesis to the stack
stack.push(char);
} else {
// Get the last opening parenthesis from the stack
let last = stack.pop();
// Check if the closing parenthesis matches the last opening parenthesis
if (char !== map[last]) {
return false;
}
}
}
// Check if the stack is empty
return stack.length === 0;
};
// Test cases
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
console.log(isValid("")); // Output: true
console.log(isValid("[")); // Output: false