干丫的算法之最长公共前缀(5)
算法薄弱,每天一道算法题,突破自己
题目
编写一个函数来查找字符串数组中的最长公共前缀
如果不存在公共前缀,返回空字符串 ""
示例1:
输入: ["flower","flow","flight"]
输出: "fl"
示例2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
解析
取第一个值为基准ans,遍历所有每一个字符,遇到不一样就停止,将ans赋值为当前长度直到结束
复杂度为 O(N) N 为所有字符串的长度和
参考代码
var longestCommonPrefix = function(strs) {
if (!strs.length) return '';
let ans = strs[0];
for (let i = 1; i < strs.length; i++) {
let j = 0;
for (; j < ans.length && j < strs[i].length; j++) {
if (ans[j] != strs[i][j]) break;
}
ans = ans.substr(0, j);
if (ans === '') return ans;
}
return ans;
};