gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:43:43 25 4
gpt4 key购买 nike

我正在尝试解决 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com