题目: Please give a function to check matching pairs of braces, parenthese and brackets
function isMatchingPair(str) {
// your code here
}
isMatchingPair('(str[x)xx]') // return false
isMatchingPair('({[str]})') // return true
题目: Please give a function to check matching pairs of braces, parenthese and brackets
function isMatchingPair(str) {
// your code here
}
isMatchingPair('(str[x)xx]') // return false
isMatchingPair('({[str]})') // return true
栈结构括号匹配。
维护一个栈结构,遍历字符串,与当前栈顶比较,若栈顶为左,遍历者为右,并且同一型号括号,则消去。非括号略过。
遍历完后若栈长度为0则说明匹配,否则不匹配。
function isMatchingPair(str){
var left = /\(|\{|\[/,right = /\)|\}|\]/,map={'(':')','{':'}','[':']'}
var stack = []
var ret = true
str.split('').forEach(function(e){
if(left.test(e)){
stack.push(e)
}else if(right.test(e)){
if(e === map[stack[stack.length - 1]]){
stack.pop()
}else{
ret = false
}
}
})
return ret && !stack.length
}
// 主要考察的数组的栈操作
function isMatchingPair(str) {
let len = str.length;
var arr1 = []; // 左括号形成的数组
let arr2 = []; // 右括号形成的数组
let obj = {
'[': ']',
'(': ')',
'{': '}'
};
const reg1 = /[\[\(\{]+/gi;
const reg2 = /[\]\)\}]+/gi;
for (let i = 0; i < len; i++) {
if (reg1.test(str.charAt(i))) {
arr1.push(str.charAt(i))
} else if (reg2.test(str.charAt(i))) {
arr2.push(str.charAt(i))
}
}
console.log(arr1, arr2);
if (arr1.length != arr2.length) {
console.log(false);
return false;
}
for (let i = 0, len = arr1.length; i < len; i++) {
console.log(i, arr1, arr2);
if (obj[arr1.shift()] != arr2.pop()) {
console.log(false);
return false;
}
}
console.log(true);
return true;
}
isMatchingPair('(str[x)xx]'); // false
isMatchingPair('({[str]})'); // true
isMatchingPair('((((str[[[x))xx])))'); // false
isMatchingPair('(({{[[str]]}}))'); // true
function isMatchingPair(str) {
// your code here
const arr = (str.replace(/[^\[\]\(\)\{\}]/g, '')).split('');
if (arr.length % 2 === 0) {
const stack = [];
arr.map(t => {
if('([{'.indexOf(t) === -1){
const temp = stack.pop();
if((temp === '[' && t === ']' )|| (temp === '(' & t === ')') || (temp === '{' & t === '}')){
return stack;
} else {
return stack.push(temp);
}
} else {
return stack.push(t);
}
});
return stack.length === 0 ? true : false;
} else {
return false;
}
}
10 回答11.2k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决