我试图在JavaScript的一组字符串中找到最长的公共子字符串。
我从Find the longest common starting substring in a set of strings那里得到了主意
但我不仅在寻找凝视的子字符串
所以,我继续进行以下操作:
我猜它可以按预期工作,但是开销为map
和sort
。
function longestCommonSubstring(array) {
// Copy the array
let arr = array.slice().sort();
// For each individual string sort them
arr = arr.map(a => a.split('').sort().join(''));
// Check the first and last string and check till chars match
let a0 = arr[0],
aLast = arr[arr.length -1],
len = arr[0].length,
i = 0;
while(i < len && a0[i] === aLast[i]) i++;
// return
return a0.substring(0,i);
}
我做错了吗?能以更有效的方式完成吗?
输入[“ abc”,“ cxabgi”]
输出[“ ab”]
答案 0 :(得分:0)
function longestCommonSubstring(array) {
const sortedArray = [...array].sort();
const firstItem = sortedArray[0];
const lastItem = sortedArray[sortedArray.length - 1];
const firstItemLength = firstItem.length;
let i = 0;
while (i < firstItemLength && firstItem.charAt(i) === lastItem.charAt(i)) {
i++;
}
return firstItem.substring(0, i);
}