write a JavaScript function :"(){}[]" => True "([{}])" => True "(}" => False "[(])" => False "[({})](]" => False
时间: 2024-04-03 10:34:06 浏览: 33
Sure! Here's a JavaScript function that can check the validity of parentheses, curly brackets, and square brackets in a given string:
```javascript
function isValid(str) {
const stack = [];
const openingChars = ['(', '{', '['];
const closingChars = [')', '}', ']'];
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (openingChars.includes(char)) {
stack.push(char);
} else if (closingChars.includes(char)) {
const matchingOpeningChar = openingChars[closingChars.indexOf(char)];
if (stack.length === 0 || stack.pop() !== matchingOpeningChar) {
return false;
}
}
}
return stack.length === 0;
}
console.log(isValid("(){}[]")); // true
console.log(isValid("([{}])")); // true
console.log(isValid("(}")); // false
console.log(isValid("[(])")); // false
console.log(isValid("[({})](]")); // false
```
This function uses a stack to keep track of the opening characters encountered in the string. Whenever a closing character is encountered, it checks if it matches the corresponding opening character at the top of the stack. If the stack is empty or the characters don't match, the function returns false. Finally, it checks if the stack is empty at the end to ensure that all opening characters had matching closing characters.
阅读全文