javascript - 一组字符串 JavaScript 中最长的公共(public)子字符串

标签 javascript arrays sorting longest-substring

我试图在 JavaScript 的一组字符串中找到最长的公共(public)子字符串。

我的想法来自 Find the longest common starting substring in a set of strings

但我不只是在寻找凝视子串

因此,我继续执行以下操作:

我猜它按预期工作,但有 mapsort 的开销。

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"]

最佳答案

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);
}

关于javascript - 一组字符串 JavaScript 中最长的公共(public)子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53928711/

相关文章:

javascript - ChatRooms 中的 ExecJS::RuntimeError#show

javascript - 访问 $.getJSON 中的对象

java - 传递数组时遇到一些问题

最近 6 个月的 SQL Server 查询

java - 大型数组的快速排序 stackoverflow 错误

javascript - Jquery:隐藏空表行

javascript - typescript 找不到名称窗口或文件

c - 重新排列字符串字母

c++ - 如何使用 std::array 模拟 C 数组初始化 "int arr[] = { e1, e2, e3, ... }"行为?

java - 关于基数排序的 Java 实现的解释