Leetcode题解之 —— 最长公共前缀

思路


暴力遍历解法

  • 找最小长度
  • every判断对应字符

题解


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
let [strsLen, result] = [strs.length, ''];

if (!strsLen) {
return result;
}

const minStrLen = strs.reduce((total, current) => {
return Math.min(total, current.length)
}, Number.MAX_VALUE);

for (let i = 0; i < minStrLen; i++) {
const strOne = strs[0][i];
const flag = strs.every((v) => {
return v[i] === strOne;
});

if (!flag) {
break;
}

result += strOne;
}

return result;
};