需求
输入 [][]{}{}
输出 true
输入 [][]{[}{]}
输出 flase
输入 ([]{})
输出 true
1
function testString(test) {
test = (test.replace(new RegExp('/[]/g'), ''))
test = (test.replace('{}', ''))
test = (test.replace('()', ''))
console.log(test, 'replace')
if (test.includes('[]') || test.includes('{}') || test.includes('()')) {
return testString(test)
} else {
console.log(test.length)
if (!test.length) {
return true;
} else {
return false;
}
}
}
console.log(testString('{[]}'))
2
function match(char) {
switch (char) {
case '[':
return ']';
case ']':
return '[';
case '(':
return ')';
case ')':
return '(';
case '{':
return '}';
case '}':
return '{';
default:
return '';
}
}
function fun(arg) {
if (arg === '') {
return true;
}
for (let i = 0; i < arg.length; i++) {
for (let j = arg.length - 1; j > i; j--) {
if (match(arg[i]) === arg[j]) {
let argInner = arg.slice(i + 1, j);
let argRight = arg.slice(j + 1);
console.log(argInner)
console.log(argRight)
if (fun(argInner) && fun(argRight)) {
return true;
} else {
return false;
}
}
}
return false;
}
}
console.log(fun('[](){()[]'))
3 这个因为没理解需求所以有错误
function confirm(input) {
if (input.length === 0) {
return false;
}
var sum1 = '';
var sum2 = '';
var sum3 = '';
for (const iterator of input) {
// console.log(iterator)
switch (iterator) {
case '[':
case ']':
sum1 += iterator;
break;
case '(':
case ')':
sum2 += iterator;
break;
case '{':
case '}':
sum3 += iterator;
break;
}
}
console.log(testString(sum1, '[]'), 'result', testString(sum2, '()'), testString(sum3, '{}'))
//
if (testString(sum1, '[]') && testString(sum2, '()') && testString(sum3, '{}')) {
return true
} else {
return false
}
}
function testString(test, type) {
console.log(test, type)
if (test.length == 0) {
console.log('falg3')
return true
}
test = (test.replace(type, ''))
console.log(test, 'replace')
if (test.includes(type)) {
return testString(test, type)
} else {
console.log(test.length)
if (!test.length) {
return true;
} else {
return false;
}
}
}
console.log(confirm('([][]{}{{}}(())))'))
在这里插入代码片
总结:
做的时间久问题出现在回调函数前没有写return