zoukankan      html  css  js  c++  java
  • js 实现最长子串算法

    代码

    
    const arr = ['weeweadbshow', 'jhsaasrbgddbshow', 'ccbshow']
    
    /**
     * 最长子串
     * 输入 ['weeweadbshow', 'jhsaasrbgddbshow', 'ccbshow'] 输出 bshow
     * @param {string[]} sourceArr
     * @return {string}
     */
    function longest(sourceArr) {
      // 字符串长度排序,优先选择最短的字符串,尽可能的减少性能开支
      sourceArr = string_ArraySort(sourceArr)
      const wholeArr = [] // 最短字符串所能产生的所有子串
      const firstStr = sourceArr.shift() // 以最短子串为基准
      let count = 0 // 结果长度
      let result = '' // 结果
    
      // 截取子串
      for (let i = 0; i < firstStr.length; i++) {
        for (let j = i + 1; j <= firstStr.length; j++) {
          wholeArr.push(firstStr.substring(i, j))
        }
      }
    
      // 遍历所有的子串
      for (let i = 0; i < wholeArr.length; i++) {
        let AllArray = [] // 建立一个结果过渡数组
    
        // 使用正则表达式来检索其他的字符串
        const patt = new RegExp(wholeArr[i])
        for (let j = 0; j < sourceArr.length; j++) {
          const reArr = sourceArr[j].match(patt) // 使用正则表达式来检索,match 函数直接返回结果
          if (reArr) { // 如果没检索到,返回一个false值,如果匹配到就返回结果
            AllArray = AllArray.concat(reArr) // 向结果过渡函数添加值
          }
        }
    
        if (AllArray.length === sourceArr.length) { // 验证是否在其他字符串中是否都匹配到了子串
          if (AllArray[0].length > count) {
            // 过渡结果
            count = AllArray[0].length
            result = AllArray[0]
          }
        }
      }
      return result
    }
    
    // 根据字符串长度排序
    function string_ArraySort(strArr) {
      return strArr.sort(function(str1, str2) {
        return str1.length - str2.length
      })
    }
    
    console.log('→', longest(arr)) // → bshow
    
    

    参考

    js 实现最长子串算法

  • 相关阅读:
    提交一个spark程序及spark执行器
    前端如何让服务器主动向浏览器推送数据
    h5页面移动端iPhoneX适配方法
    详说tcp粘包和半包
    mysql配置文件 /etc/my.cnf 详细解释
    【todo】MVCC原理及与锁之间的关系
    【todo】innodb表锁的底层实现原理
    【todo】innodb行锁的底层实现原理
    【todo】mysql binlog
    [todo] spring 事务的传播性
  • 原文地址:https://www.cnblogs.com/taohuaya/p/14981942.html
Copyright © 2011-2022 走看看