javascript - Javascript 中最长的公共(public)前缀

标签 javascript arrays string for-loop if-statement

我正在尝试解决 Leet Code 挑战 14. Longest Common Prefix :

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""

Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

我的解决方案:

let strs = ["flower", "flow", "flight"];

var longestCommonPrefix = function (strs) {
  for (let i = 0; i < strs.length; i++) {
    for (let j = 0; j < strs[i].length; j++) {
       // console.log(strs[i+2][j]);
      if (strs[i][j] == strs[i + 1][j] && strs[i + 1][j] ==strs[i + 2][j]) {
        return (strs[i][j]);
        
      } else {
        return "0";
      }
    }
  }
};

console.log(longestCommonPrefix(strs));

输出:f如何遍历每个字符并检查它是否相同,然后继续下一步,如果失败,则将返回最长的公共(public)前缀?

最佳答案

由于最长的公共(public)前缀必须出现在数组的每个字符串中,您可以迭代长度并检查所有单词在该索引处是否具有相同的字符,直到找到差异

function prefix(words){
  // check border cases size 1 array and empty first word)
  if (!words[0] || words.length ==  1) return words[0] || "";
  let i = 0;
  // while all words have the same character at position i, increment i
  while(words[0][i] && words.every(w => w[i] === words[0][i]))
    i++;
  
  // prefix is the substring from the beginning to the last successfully checked i
  return words[0].substr(0, i);
}

console.log(1, prefix([]));
console.log(2, prefix([""]));
console.log(3, prefix(["abc"]));
console.log(4, prefix(["abcdefgh", "abcde", "abe"]));
console.log(5, prefix(["abc", "abc", "abc"]));
console.log(6, prefix(["abc", "abcde", "xyz"]));

关于javascript - Javascript 中最长的公共(public)前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68702774/

相关文章:

javascript - Algolia - 获取所有唯一标签及其总数

c++ - 这会导致内存泄漏,从函数返回数组吗?

c 在泛型数组中搜索

PHP 数组随机播放 HTML 链接

java - 二进制到Java中的文本

c++ - 从一个句子中逐字打印

javascript - Jquery Ajax 改变 html 表的内容

javascript - 如何找到鼠标在网页上的准确位置

javascript - 使用 LESS 和 jQuery 等宽和等高

java - 如何检查一个字符串是否包含另一个字符串的一部分? (不是整个字符串)