-
Notifications
You must be signed in to change notification settings - Fork 738
/
Copy pathdemo.js
36 lines (33 loc) · 1018 Bytes
/
demo.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
function isValid(s) {
const stack = [];
for (let char of s) {
switch (char) {
case '(': case '[': case '{':
// If the character is an opening bracket, push it onto the stack.
stack.push(char);
break;
case ')':
if (stack.pop() !== '(') {
return false; // Mismatched closing bracket.
}
break;
case ']':
if (stack.pop() !== '[') {
return false; // Mismatched closing bracket.
}
break;
case '}':
if (stack.pop() !== '{') {
return false; // Mismatched closing bracket.
}
break;
default:
// If the character is not a bracket, ignore it.
}
}
// After processing all characters, the stack should be empty if the string is valid.
return stack.length === 0;
}
console.log(isValid("()")); // true
console.log(isValid("()[]{}")); // true
console.log(isValid("(]")); // false