首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >搜索通用子字符串

搜索通用子字符串
EN

Stack Overflow用户
提问于 2018-10-23 01:49:29
回答 1查看 70关注 0票数 0

该脚本在字符串数组中搜索最大的子字符串。但是如果字符串不是以"A“开头,搜索就会失败。如何实现内置子字符串的搜索?("ABCDE","XBCDJL") = BCD

代码语言:javascript
复制
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;
    }
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-23 02:20:15

你可以试试下面的

代码语言:javascript
复制
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));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52934992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档