题解 | #最长公共子串#

最长公共子串

http://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

/**
 * longest common substring
 * @param str1 string字符串 the string
 * @param str2 string字符串 the string
 * @return string字符串
 */
function LCS( str1 ,  str2 ) {
    // write code here
    const arr1 = str1.split("")
  const arr2 = str2.split("")

  const strTemp = []

  let str = ""

  for( let i = 0, l1 = arr1.length; i < l1; i++ ) {

    const item1 = arr1[i]
 
    strTemp[i] = []

    for( let j = 0, l2 = arr2.length; j < l2; j++ ) {

      const item2 = arr2[j]

      strTemp[i][j] = ""

      if( item1 === item2 ) {

        if(i > 0 && j > 0){
          strTemp[i][j] = strTemp[i-1][j-1] ? strTemp[i-1][j-1] + item2 : item2 ;
        }else {
          strTemp[i][j] = item2;
        }

        if( strTemp[i][j].length > str.length ) {
          str = strTemp[i][j]
        }

      }

    }

  }

  return str
}
module.exports = {
    LCS : LCS
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:30
点赞 评论 收藏
分享
程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务