Skip to content

Commit eac4f85

Browse files
author
phillzou
committed
feat: add longest common prefix
1 parent d7c81cc commit eac4f85

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
- [堆排序](./src/heapSort.js)
5858
- [二分查找](./src/binarySearch.js)
5959
- [最长递增子序列](./src/lis.js) ★★★
60+
- [最长公共子串](./src/longestCommonPrefix.js) ★★
6061

6162

6263
分享一下自己整理的 LeetCode 上必刷的题,比较具有代表性。

src/longestCommonPrefix.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function longestPrefix(arr) {
2+
if (arr.length === 0) {
3+
return '';
4+
}
5+
let prefix = arr[0];
6+
for (let i = 1; i < arr.length; i++) {
7+
while (arr[i].indexOf(prefix) !== 0) {
8+
prefix = prefix.substring(0, prefix.length - 1);
9+
if (prefix.length === 0) {
10+
return '';
11+
}
12+
}
13+
}
14+
return prefix;
15+
}
16+
17+
// test
18+
let strs = ['helly', 'hellow', 'hell'];
19+
20+
console.log(longestPrefix(strs)); // hell

0 commit comments

Comments
 (0)