在看下面试题之前,我们先来测测吧?戳我测试!
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。

取出第一项,然后从第二项开始依次通过startsWith判断,是否以从第一项截取的字符串开头
const longestCommonPrefix = function (strs) {
if (!strs || !strs.length) {
return '';
}
const str = strs[0];
let index = 0;
while (index < str.length) {
// 从第一项截取前缀
const prefix = str.slice(0, index + 1);
// 判断后面的项是否都含有此前缀
for (let i = 1; i < strs.length; i++) {
// 不以此前缀开头时,返回结果
if (!strs[i].startsWith(prefix)) {
return str.slice(0, index);
}
}
index++;
}
return str;
};
longestCommonPrefix(); // ""
longestCommonPrefix([]); // ""
longestCommonPrefix(["flower","flow","flight"]); // "fl"
longestCommonPrefix(["dog","racecar","car"]); // ""
longestCommonPrefix(["dog"]); // "dog"