We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d7c81cc commit eac4f85Copy full SHA for eac4f85
README.md
@@ -57,6 +57,7 @@
57
- [堆排序](./src/heapSort.js) ★
58
- [二分查找](./src/binarySearch.js) ★
59
- [最长递增子序列](./src/lis.js) ★★★
60
+- [最长公共子串](./src/longestCommonPrefix.js) ★★
61
62
63
分享一下自己整理的 LeetCode 上必刷的题,比较具有代表性。
src/longestCommonPrefix.js
@@ -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
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