括号问题也是时常被考到的问题,在这里我们来看三道关于括号匹配的问题
老规矩,先来道简单的压压惊
20. 有效的括号
分析
- 对于这类题目,我们一般使用栈的数据解构来配合解答
代码
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
//创建一个栈
let stack = []
for(let c of s) {
if(c==='(' || c=== '{' || c==='[') {
stack.unshift(c);
} else {
if(stack.length!=0 && match(c)===stack[0]) {
stack.shift();
} else {
return false;
}
}
}
return stack.length===0;
};
var match = function(c) {
if(c===')') return '(';
if(c==='}') return '{'
return '['
}
接下来我们再来看一题
- 这道题还是比较简单的,只涉及到了一种括号
- 核心思路是以左括号为基准,通过维护对右括号的需求数 need,来计算最小的插入次数
- 注意:need == -1时,说明此时的右括号太多了,没有对应的左括号补充,这个数据也是需要我们记录的
代码
/**
* @param {string} s
* @return {number}
*/
var minAddToMakeValid = function(s) {
let res = 0, need = 0;
for(let c of s) {
if(c==='(') {
need++;
} else {
need--;
if(need == -1) {
need = 0;
res++;
}
}
}
return res+need;
};
再看看上一道题的升级版
分析
- 这道题与上面那题不同点是这道题的一个左括号需要两个右括号
- 我们只需要将消除括号的方式改变一下
- 注意:这里如果要判断右括号是否剩余一个,剩余一个(与剩余两个处理方式不同)要进行另外的处理
代码
/**
* @param {string} s
* @return {number}
*/
var minInsertions = function(s) {
let res = 0, need = 0;
for(let c of s) {
if(c==='(') {
need+=2;
if(need % 2 == 1) {
res++;
need--;
}
} else {
need--;
if(need === -1) {
need = 1;
res++; //左括号+1
}
}
}
return res + need;
};
以上题解参考labuladong的算法秘籍