14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function longestCommonPrefix(strs: string[]): string {
let res = '';
if (strs.length === 1) return strs[0];
const target = strs[0];
let len = target.length;
for(let i = 0; i < len; i++) {
let isSame = false;
for(let j = 1; j < strs.length; j++) {
if (target[i] !== strs[j][i]) {
isSame = false;
break;
}
isSame = true;
}
if (isSame) {
res += target[i];
} else {
break;
}
}

return res;
};