给出一个仅包含两种类型字符的字符串:“(” 和“)” 。通过根据需要多次插入“(” 或“)” 来平衡括号。
确定必须插入的最小字符数。 示例s = “(()))” 。为了使序列有效,应该在开头插入一个“(” 。现在,在插入一次字符串之后,该字符串将保持平衡。答案为1。
我在这里的问题是,我尝试使字符串有效,但无法确定最小插入次数,应该使序列有效。
let output = [];
function checkParanthesis(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === "(") {
output.push(str[i]);
count++;
} else if (str[i] === ")") {
if (output.pop() !== "(") {
count++
}
}
console.log(count);
}
return output.length;
}
checkParanthesis('()))')
答案 0 :(得分:1)
这是递归的解决方案,还具有根据结果对原始字符串进行 correct 的功能
let output = [];
function checkParanthesisRec(str, count, curr, iter) {
if(str.length === 0){
return {
count: count,
correction: iter
};
}
if(str.substr(0,1) === ')'){
iter[curr] = '(';
count++
}else{
var closing = str.indexOf(')');
if(closing != -1){
str = str.substr(0, closing) + str.substr(closing+1);
}else{
iter[curr] = ')';
count++
}
}
return checkParanthesisRec(str.substr(1), count, curr+1, iter);
}
function checkParanthesis(str){
return checkParanthesisRec(str, 0, 0, {});
}
var test = '()))';
var res = checkParanthesis(test);
console.log(res.count);
function correctParenthesis(str, correction){
var invertedPositions = Object.keys(correction).map((k) => parseInt(k)).sort(function(a, b){return b-a});
invertedPositions.forEach((p) => {
str = str.substr(0, p) + correction[p] + str.substr(p);
});
return str;
}
console.log(correctParenthesis(test, res.correction));
答案 1 :(得分:1)
一种更简单的方法?
function countMissingParenthese(parenthesesString) {
var temp=parenthesesString;
var temp2="";
var done=false;
while(!done) {
temp2=temp.split("()").join("");
done=(temp2.length==temp.length);
temp=temp2;
}
console.log(temp);
return temp.length;
}
该函数删除“()”,记录剩余量,并返回剩余量。
它不会告诉您缺少的内容和位置-但您没有要求。
可能的失败者注意事项:
请详细解释原因。
不要成为巨魔。
谢谢!
答案 2 :(得分:0)
您可以采用数组来跟踪最后一个左括号,如果找到了一个右括号,则将其删除。
对于未找到的右括号,请在数组中添加其他字符,然后返回数组的长度。
function checkParanthesis(str) {
let brackets = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === "(") {
brackets.push(str[i]);
} else if (str[i] === ")") {
if (brackets[brackets.length - 1] === "(") brackets.pop();
else brackets.push("#");
}
}
return brackets.length;
}
console.log(checkParanthesis('()))'));
答案 3 :(得分:0)
JavaScript 中的简单解决方案
/**
* @param {string} s
* @return {boolean}
*/
var checkParanthesis = function(s) {
if(typeof s !== "string" || s.length % 2 !== 0) return false;
let i = 0;
let arr = [];
while(i<s.length) {
if(s[i]=== "{" || s[i]=== "(" || s[i]=== "[") {
arr.push(s[i]);
} else if(s[i] === "}" && arr[arr.length-1] === "{") {
arr.pop()
} else if(s[i] === ")" && arr[arr.length-1] === "(") {
arr.pop()
} else if(s[i] === "]" && arr[arr.length-1] === "[") {
arr.pop()
} else {
return false;
}
i++
}
return arr.length === 0;
};
let str = "{([])}";
console.log(checkParanthesis(str))
时间复杂度 O(n)