今天也尝试写一下最长公共子串,基本思路就是穷举,找到两个串中相等的元素,然后把它们的index记录下来,再通过for-in循环求出最长的子串,
2018-4-4 今天早上的这段代码目前能求出最长长度,尚不完善。
2018-4-6 已经可以得到公共字串的长度和详细数据了
function mostLong ( arr1,arr2 ){ let result = {}; var arr1Length = arr1.length ; var arr2length = arr2.length; for(let i = 0; i < arr1Length; i++ ){ for( let j = 0 ; j < arr2length; j++ ){ if( arr1[i] === arr2[j] ){ result[i + '$' + j] = { isMatch:true, } } } } result let subsequence = { length:0, key:[] };//子序列 for (let key in result) { if (result.hasOwnProperty(key)) { let index1 = key.split('$')[0] //第一个数组的下标 let index2 = key.split('$')[1]; var count = 0// while( result[index1 + '' + index2] ){ count++; if( count > subsequence.length ){ subsequence.length = count; let temp1 = index1,temp2=index2,//向上追迹 已经遍历过的数据 temp = []; for(;result[temp1 + '$' + temp2];){ temp.push(temp1 + '$' + temp2); temp1--; temp2-- } temp.reverse(); subsequence.key = temp; index1++; index2++; }else{ index2++; index1++; } } } } return subsequence }