javascript - 搜索公共子字符串
问题描述
该脚本在字符串数组中搜索最大的子字符串。但如果字符串不以“A”开头,则搜索失败。如何实现里面的子串搜索?("ABCDE", "XBCDJL") = BCD
var array = ["ABCDEFZ", "ABCDXYZ"],
prefix = array[0],
len = prefix.length;
for (i=1; i<array.length; i++) {
for (j=0, len=Math.min(len,array[j].length); j<len; j++) {
if (prefix[j] != array[i][j]) {
len = j;
prefix = prefix.substr(0, len);
break;
}
}
}
解决方案
您可以尝试以下
var array = ["ABCDEFZ", "EBCDXYZ"];
/* In case there is a match, it has to exist in the first string as well.
* So, irrespective of the length of first string,
* we will do our iterations w.r.t. its length */
function findLargestSubstr(arr) {
if(!arr.length) return;
let length = arr[0].length; // length over the first item in array
let val; // value that will be returned
/* looping through the length of first element combinations
* where the first combination will be the complete string and
* the second will be 1 less than the length and then so on */
outer: for (let i = length; i > 0; i--) {
// For every iteration, create the subset of substring that need to be checked
for (let j=0; j <= length - i; j++) {
// Get the substring
let temp = arr[0].substr(j, i);
// Check for the substring for every element in the array
if(arr.every(v => v.includes(temp))) {
/* If the match is found, then
* set the return value to the match and break the loop's */
val = temp;
break outer;
}
}
}
return val;
}
console.log(findLargestSubstr(array));
推荐阅读
- python - Python Kivy 返回'AttributeError:'super'对象没有属性'__getattr__''
- php - 不同配置文件中的相同视图 Laravel
- javascript - 光滑的轮播,图像没有滑动
- php - (PHP+MySQL) 在数据库中保存字符集错误,但解码正确
- python - 如何在没有尾随换行符的情况下打印?
- ckeditor5 - 升级 ckeditor 软件包后无法输入所见即所得编辑器
- abp - 依赖项目的 abp.io AddRazorRuntimeCompilation
- python - 匹配多边形内的纬度/经度点
- python - 转换为 Int 后,Pycharm 仍在数据框中显示浮点数
- gcc - 不受支持的 GNU 版本!不支持高于 7 的 gcc 版本