Skip to content

Commit b8bdb9b

Browse files
committedSep 20, 2021
Add solution #14
1 parent f1759aa commit b8bdb9b

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
3|[Longest Substring Without Repeating Characters](./0003-longest-substring-without-repeating-characters.js)|Medium|
1212
4|[Median of Two Sorted Arrays](./0004-median-of-two-sorted-arrays.js)|Hard|
1313
7|[Reverse Integer](./0007-reverse-integer.js)|Easy|
14+
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
1415
27|[Remove Element](./0027-remove-element.js)|Easy|
1516
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1617
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 14. Longest Common Prefix
3+
* https://leetcode.com/problems/longest-common-prefix/
4+
* Difficulty: Easy
5+
*
6+
* Write a function to find the longest common prefix string amongst an array of strings.
7+
*
8+
* If there is no common prefix, return an empty string `""`.
9+
*/
10+
11+
/**
12+
* @param {string[]} strs
13+
* @return {string}
14+
*/
15+
var longestCommonPrefix = function(strs) {
16+
const prefixes = strs[0].split('').map((_, i) => strs[0].slice(0, i + 1));
17+
18+
for (let i = strs.length - 1; i > -1; i--) {
19+
for (let j = prefixes.length - 1; j > -1; j--) {
20+
if (strs[i].substr(0, j + 1) !== prefixes[j]) {
21+
prefixes.pop();
22+
}
23+
}
24+
}
25+
26+
return prefixes.pop() || '';
27+
};

0 commit comments

Comments
 (0)
Please sign in to comment.