括号编号及其在字符串中的位置无效



我正在查找无效括号的数量及其位置。我使用了一个数组来保存无效的括号位置号。但是myArray.pop((没有触发。

function processData(input) {
var myArray = [];
var paranthesisIndex = 0;
for (C of input) {
paranthesisIndex++
if (C === '(') {
myArray.push(paranthesisIndex);
} else if (C === ')') {
if (myArray.length < 0 && myArray[myArray.length - 1] === '(') {
myArray.pop() //not working
} else {
myArray.push(paranthesisIndex)
}
}
}
console.log(myArray.length)
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i])
}
}
processData("())()");

输出

5
1
2
3
4
5

预期输出

1
3

您使用了if( myArray.length<0 ...,所以您的代码永远不会运行,因为数组应该没有元素才能运行if块。也许你想使用if( myArray.length> 0 ...

最新更新