File tree 2 files changed +28
-0
lines changed
2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change 11
11
3|[ Longest Substring Without Repeating Characters] ( ./0003-longest-substring-without-repeating-characters.js ) |Medium|
12
12
4|[ Median of Two Sorted Arrays] ( ./0004-median-of-two-sorted-arrays.js ) |Hard|
13
13
7|[ Reverse Integer] ( ./0007-reverse-integer.js ) |Easy|
14
+ 14|[ Longest Common Prefix] ( ./0014-longest-common-prefix.js ) |Easy|
14
15
27|[ Remove Element] ( ./0027-remove-element.js ) |Easy|
15
16
31|[ Next Permutation] ( ./0031-next-permutation.js ) |Medium|
16
17
36|[ Valid Sudoku] ( ./0036-valid-sudoku.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments