javascript - A front-end interview question, solution
習慣沉默
習慣沉默 2017-05-19 10:18:37
0
5
639

题目: 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
習慣沉默
習慣沉默

reply all(5)
左手右手慢动作
function isMatchingPair(str) {     
    var s = [];
    var l = ['(','[','{'];
    var r = [')',']','}'];
    for(var i = 0; i< str.length; i++){
        if(l.includes(str[i]))
            s.push(r[l.indexOf(str[i])]);
        if(r.includes(str[i]))
            if(s.pop()!=str[i]){return false;}
    }
    return s.length?false:true;
}
某草草

Stack structure bracket matching.

Maintain a stack structure, traverse the string, and compare it with the current top of the stack. If the top of the stack is left, the traverser is right, and the brackets are of the same type, they are eliminated. Non-parentheses are ignored.

After traversing, if the stack length is 0, it means there is a match, otherwise it does not match.

给我你的怀抱
 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
黄舟

Wow, can you ask where the interview questions are? It still feels not easy

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template