Appearance
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/longest-common-prefix
javascript
/**
* @param {string[]} strs
* @return {string}
*/
// 解法一 遍历
var longestCommonPrefix = function (strs) {
if (strs.length === 1) return strs[0]
var minStr = strs[0],
minStrIndex = 0,
prefix = ""
for (var i = 1; i < strs.length; i++) {
if (strs[i].length < minStr.length) {
minStr = strs[i]
minStrIndex = i
}
}
for (var j = minStr.length; j >= 0; j--) {
prefix = minStr.slice(0, j)
if (strs.every((item) => item.startsWith(prefix))) {
return prefix
}
}
}
console.log(longestCommonPrefix(["flower", "flow", "flight"]) === "fl")
console.log(longestCommonPrefix(["dog", "racecar", "car"]) === "")
console.log(longestCommonPrefix(["ab", "a"]) === "a")
console.log(
longestCommonPrefix(["flower", "flower", "flower", "flower"]) === "flower"
)
console.log(
longestCommonPrefix(["flower", "flower", "flower", "flower", ""]) === ""
)