-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
33 lines (30 loc) · 912 Bytes
/
test.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
function isValid(s) {
const stack = [];
const map = {
"(": ")",
"{": "}",
"[": "]",
};
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (map[char]) {
// If the character is an opening bracket, push it onto the stack
stack.push(char);
} else {
// If the character is a closing bracket, check if it matches the top of the stack
const top = stack.pop();
if (map[top] !== char) {
return "invalid";
}
}
}
// If the stack is empty, all brackets were matched correctly
return stack.length === 0 ? "valid" : "invalid";
}
// Example usage:
console.log(isValid("()")); // Output: valid
console.log(isValid("()[]{}")); // Output: valid
console.log(isValid("(]")); // Output: invalid
console.log(isValid("([)]")); // Output: invalid
console.log(isValid("{[]}")); // Output: valid
console.log(isValid("[]")); // Output: valid