Last active
July 7, 2017 01:36
-
-
Save panweizeng/6680088 to your computer and use it in GitHub Desktop.
编写函数获取两个字符串的最长公共子串,例如: s1 = GCCCTAGCCAGDE,s2 = GCGCCAGTGDE,它们的最长公共子串是 GCCAG。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getMaxSub(s1, s2) { | |
var max = 0, retchars = []; | |
for(var index = 0; index < s1.length; index++){ | |
var count = 0, chars = []; // 每次遍历都置空 | |
debug('============%d============', index); | |
for(var i = index, j = 0; j < s2.length; j++){ | |
var s1char = s1[i]; | |
var s2char = s2[j]; | |
debug(s1char, s2char, s1char === s2char); | |
if(s1char === s2char){ | |
count++; | |
i++; | |
chars.push(s1char); | |
} else if(count) { // 如果不相同且有相同过则count和chars置空,i复位,j回退一位 | |
j--; | |
count = 0; | |
chars = []; | |
i = index; | |
} | |
debug('max:%d, count:%d, i:%d, j:%d', max, count, i, j); | |
if(count > max) { | |
max = count; | |
debug(chars); | |
retchars = chars.slice(); | |
} | |
} | |
} | |
return retchars.join(''); | |
} | |
// =================== test =================== | |
var arr = [ | |
[ | |
'GCCCTAGCCAGDE', | |
'GCGCCAGTGDE', | |
'GCCAG' // middle | |
], | |
[ | |
'GCGCCAGTGDE', | |
'GCCCTAGCCAGDE', | |
'GCCAG' // middle | |
], | |
[ | |
'GCCCTAGCCAGDE', | |
'GCCCTAGCCA', | |
'GCCCTAGCCA' // prefix | |
], | |
[ | |
'GCCCTAGCCAGDE', | |
'GCCAGDE', | |
'GCCAGDE' // suffix | |
], | |
[ | |
'AGCCCTAGCCAGDE', | |
'BCGCCCTAGCCA', | |
'GCCCTAGCCA' // mix | |
], | |
[ | |
'GCCCTAGCCAGDE', | |
'ZZZXXX', | |
'' // no common | |
], | |
[ | |
'abcdefghijklmn', | |
'abcdefghijklmn', | |
'abcdefghijklmn' // same | |
], | |
[ | |
'abcdefghijklmn', | |
'n', | |
'n' // single char | |
], | |
[ | |
'', | |
'n', | |
'' // blank | |
], | |
[ | |
'', | |
'', | |
'' // blank | |
] | |
]; | |
function debug(msg){ | |
if(debug.on){ | |
console.info.apply(this, arguments); | |
} | |
} | |
debug.on = 0; | |
if(0){ | |
var item = arr[3]; | |
var result = getMaxSub(item[0], item[1]); | |
console.info(result, item[2]); | |
console.info((result == item[2]) ? 'TRUE' : 'FALSE', item[0], item[1], item[2]); | |
process.exit(); | |
} | |
for(var i = 0; i < arr.length; i++) { | |
var item = arr[i]; | |
var result = getMaxSub(item[0], item[1]); | |
console.info((result == item[2]) ? 'TRUE' : 'FALSE', item[0], item[1], item[2]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment