Skip to content

Commit e2f814d

Browse files
committed
Longest Common Prefix
1 parent 054c27d commit e2f814d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
|1|[两数之和](https://leetcode-cn.com/problems/two-sum/)|[JavaScript](./algorithms/two-sum.js)|Easy|
66
|2|[两数相加](https://leetcode-cn.com/problems/add-two-numbers/)|[JavaScript](./algorithms/add-two-numbers.js)|Medium|
77
|9|[回文数](https://leetcode-cn.com/problems/palindrome-number/)|[JavaScript](./algorithms/palindrome-number.js)|Easy|
8-
8+
|14|[最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)|[JavaScript](./algorithms/longest-common-prefix.js)|Easy|

algorithms/longest-common-prefix.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function (strs) {
6+
if (!strs[0].length) {
7+
return "";
8+
}
9+
10+
const first = strs[0];
11+
12+
for (let i = 0; i <= first.length; i++) {
13+
for (let j = 1; j < strs.length; j++) {
14+
if (first[i] !== strs[j][i]) {
15+
return first.slice(0, i);
16+
}
17+
}
18+
}
19+
};

0 commit comments

Comments
 (0)