File tree 2 files changed +35
-0
lines changed
LeetcodeProblems/Algorithms
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ Longest Common Prefix
3
+ https://leetcode.com/problems/longest-common-prefix/
4
+
5
+ Write a function to find the longest common prefix string amongst an array of strings.
6
+
7
+ If there is no common prefix, return an empty string "".
8
+
9
+ Example 1:
10
+ Input: strs = ["flower","flow","flight"]
11
+ Output: "fl"
12
+
13
+ Example 2:
14
+ Input: strs = ["dog","racecar","car"]
15
+ Output: ""
16
+ Explanation: There is no common prefix among the input strings.
17
+
18
+ */
19
+
20
+ /**
21
+ * @param {string[] } strs
22
+ * @return {string }
23
+ */
24
+ var longestCommonPrefix = function ( strs ) {
25
+ if ( strs . length === 0 ) return "" ;
26
+
27
+ return strs . reduce ( ( result , curr ) => {
28
+ let i = 0 ;
29
+ while ( result [ i ] && curr [ i ] && result [ i ] === curr [ i ] ) i ++ ;
30
+ return result . slice ( 0 , i ) ;
31
+ } ) ;
32
+ } ;
33
+
34
+ module . exports . longestCommonPrefix = longestCommonPrefix ;
Original file line number Diff line number Diff line change @@ -76,6 +76,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
76
76
| [ Binary Gap ] ( /LeetcodeProblems/Algorithms/Binary_Gap.js ) | Easy | https://leetcode.com/problems/binary-gap/ |
77
77
| [ Binary Gap ] ( /LeetcodeProblems/Algorithms/Binary_Gap.js ) | Easy | https://leetcode.com/problems/binary-gap/ |
78
78
| [ Majority Element] ( /LeetcodeProblems/Algorithms/Majority_Element.js ) | Easy | https://leetcode.com/problems/majority-element/ |
79
+ | [ Longest Common Prefix] ( /LeetcodeProblems/Algorithms/Longest_Common_Prefix.js ) | Easy | https://leetcode.com/problems/longest-common-prefix/ |
79
80
| [ Tic Tac Toe ] ( /LeetcodeProblems/Algorithms/Tic_Tac_Toe.js ) | | |
80
81
| [ Permutations With Duplicates ] ( /LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js ) | | |
81
82
| [ Deletion Distance] ( /LeetcodeProblems/Algorithms/Deletion_Distance.js ) | | |
You can’t perform that action at this time.
0 commit comments