编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
function longestCommonPrefix(strs: string[]): string {
if (strs.length === 0) return "";
// 1. 找到长度最短的字符串作为初始前缀(可选,不找也可以,直接用 strs[0])
let prefix = strs.reduce((a, b) => (a.length <= b.length ? a : b));
for (let i = 0; i < strs.length; i++) {
// 更新 prefix 为当前前缀与 strs[i] 的公共前缀
prefix = getPrefix(strs[i], prefix);
// 如果前缀已经变为空,直接跳出循环
if (prefix === "") return "";
}
return prefix;
}
function getPrefix(str: string, currentPrefix: string): string {
// 如果当前字符串不以 prefix 开头,则不断缩短 prefix
while (!str.startsWith(currentPrefix) && currentPrefix !== "") {
currentPrefix = currentPrefix.slice(0, -1);
}
return currentPrefix;
}