Skip to content

Instantly share code, notes, and snippets.

@ifyour
Last active November 19, 2021 10:03
Show Gist options
  • Save ifyour/718a21a0cf068244176693a4cce1b564 to your computer and use it in GitHub Desktop.
Save ifyour/718a21a0cf068244176693a4cce1b564 to your computer and use it in GitHub Desktop.
// 检测给定字符串是否正确嵌套
// Determine whether a given string of parentheses (multiple types) is properly nested.
function solution(text) {
var openBrackets = ['(', '[', '<', '{'];
var closedBrackets = [')', ']', '>', '}'];
var requiredClosedBrackets = [];
var chars = text.split('');
for (var i = 0; i < chars.length; i++) {
for (var j = 0; j < openBrackets.length; j++) {
if (chars[i] == openBrackets[j]) {
requiredClosedBrackets.push(closedBrackets[j]);
} else if (chars[i] == closedBrackets[j]) {
if (chars[i] != requiredClosedBrackets[requiredClosedBrackets.length - 1]) {
return 0;
} else {
requiredClosedBrackets.pop();
}
}
}
}
return (requiredClosedBrackets.length == 0) ? 1 : 0;
}
@ifyour
Copy link
Author

ifyour commented Nov 19, 2021

验证一个表达式字符串:

solution('[xxx] + ([xxx] - [bbbb]) * 1 / {456} - [{xxx}]')
1
solution('[xxx] + ([xxx] - [bbbb]) * 1 / {456} - [{xxx]')
0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment