Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 68cecc8

Browse files
author
ongch
committed
add: longest common prefix
1 parent 675f694 commit 68cecc8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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;

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
7676
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
7777
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
7878
| [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/ |
7980
| [Tic Tac Toe ](/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js) | | |
8081
| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | |
8182
| [Deletion Distance](/LeetcodeProblems/Algorithms/Deletion_Distance.js) | | |

0 commit comments

Comments
 (0)