Interview
Interview copied to clipboard
Day360:给定一个字符串str,只会出现{}()[]这6种字符,请实现一个函数isMatch(str)判断这个字符串中的括号是否是匹配的?
例如以下字符串均为括号匹配的:(){()[{}]} ()({}) {()}[]{()} [{{[()]}}]。
function isLeft (char) {
return ({'(' : 1, '{': 2, '[': 3})[char] || 0;
}
function isRight (char) {
return ({')' : 1, '}': 2, ']': 3})[char] || 0;
}
function isMatch(str) {
let stack = [];
let len = str.length;
let i = 0;
while (i < len) {
let char = str[i];
if (isLeft(char)) {
stack.push(char)
}
let rightCode = isRight(char);
if (rightCode) {
if (isLeft(stack.pop()) !== rightCode) {
return false;
}
}
i++;
}
return !stack.length;
}
let str = '(){()[{}]}()({}){()}[]{()}[{{[()]}}]';
console.log(isMatch(str))
str = '(){()[{}]}()({}){()}[]{()}[{{[()]}}]}';
console.log(isMatch(str))
大佬这些题是怎么弄到的呀
大佬这些题是怎么弄到的呀
网友分享和投稿的,哈哈,欢迎分享题目哈!