代码之家  ›  专栏  ›  技术社区  ›  totalnoob

检查javascript中字符串的两边是否相等

  •  0
  • totalnoob  · 技术社区  · 7 年前

    我想编写一个函数来测试如果两边的字符串是相反的,那么像“()”或“<<>>”这样的字符串在两边是否相等。像“(()”这样的东西是假的

    出于某种原因,reverse在将其拆分为数组后不会对right执行任何操作?

    function ifEqual(str) {
      let left = str.slice(0, str.length / 2);
      let right = str.slice(str.length / 2).split("").reverse().join("");
      console.log(left);
      console.log(right);
    
      return left === right;
    }
    
    ifEqual("(())")
    4 回复  |  直到 7 年前
        1
  •  1
  •   codechella    6 年前

    也许你在找平衡括号

    var balancedParens = function(str) {
      var stack = [];
      var open = { '{': '}', '[': ']', '(': ')' };
      var closed = { '}': true, ']': true, ')': true };
      
      for (var i = 0; i < str.length; i ++) {
        var chr = str[i];
        if (open[chr]) {
          stack.push(chr);
        } else if (closed[chr]) {
          if (open[stack.pop()] !== chr) return false;
        }
      }
      
      return stack.length === 0;
    };

    https://medium.com/@robhitt/balance-parenthesis-in-javascript-60f451a00c4c

        2
  •  1
  •   Tomasz Bubała    7 年前

    < > 等等,然后通过一个函数运行字符串,该函数接受字符串的一半,并检查另一半(按正确的顺序)是否由它的对立面组成。请注意,如果长度是均匀的,则下面的解决方案有效。

    const opposites = {
      "(": ")",
      ")": "(",
      "<": ">",
      ">": "<",
      "[": "]",
      "]": "["
    };
    function isMirrored(str) {
      const half = str.slice(0, str.length / 2);
      const reversed = half.split("").reverse().join("");
      let mirrored = half;
      for(char of reversed) {
        mirrored += opposites[char];
      }
      return str === mirrored;
    }
    console.log(isMirrored("[[]]"));
    console.log(isMirrored("<<>>"));
    console.log(isMirrored("<()>"));
    console.log(isMirrored("([]("));
    console.log(isMirrored("(())"));
        3
  •  1
  •   sellmeadog    7 年前

    const REVERSED = {
      "(": ")",
      "<": ">",
      "[": "]",
    }
    
    function ifEqual(str) {
      let left = str.slice(0, str.length / 2).split('');
      let right = str.slice(str.length / 2, str.length).split('');
      
      return left.every((next, index) => REVERSED[next] == right[right.length - index - 1])
    }
    
    console.log(ifEqual("(())"))
    console.log(ifEqual("<(>>"))
    console.log(ifEqual("<[[(())]]>"))
        4
  •  0
  •   Calvin Nunes    7 年前

    (())

    function ifEqual(str) {
        return str === str.split("").reverse().join("")
    }
    console.log(ifEqual("(())"))