Skip to content

Commit e4c6481

Browse files
ongzxongchignacio-chiazzo
authored
add: longest common prefix (ignacio-chiazzo#52)
* add: longest common prefix * add: test Co-authored-by: ongch <ongch@sea.com> Co-authored-by: Ignacio Chiazzo Cardarello <ignaciochiazzo@gmail.com>
1 parent ed4f498 commit e4c6481

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-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;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
const assert = require('assert');
3+
const longestCommonPrefix = require('../../LeetcodeProblems/Algorithms/Longest_Common_Prefix').longestCommonPrefix;
4+
5+
function test() {
6+
assert.equal(longestCommonPrefix(["flower","flow","flight"]), "fl");
7+
assert.equal(longestCommonPrefix(["dog","racecar","car"]), "");
8+
assert.equal(longestCommonPrefix([]), "");
9+
}
10+
11+
module.exports.test = test;

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ To run a specific problem in your console run `node <problem_file_path>` (e.g.
7979
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
8080
| [Binary Gap ](/LeetcodeProblems/Algorithms/Binary_Gap.js) | Easy | https://leetcode.com/problems/binary-gap/ |
8181
| [Majority Element](/LeetcodeProblems/Algorithms/Majority_Element.js) | Easy | https://leetcode.com/problems/majority-element/ |
82+
| [Longest Common Prefix](/LeetcodeProblems/Algorithms/Longest_Common_Prefix.js) | Easy | https://leetcode.com/problems/longest-common-prefix/ |
8283
| [Two Sum](/LeetcodeProblems/Algorithms/2Sum.js) | Easy | https://leetcode.com/problems/two-sum/ |
8384
| [Tic Tac Toe ](/LeetcodeProblems/Algorithms/Tic_Tac_Toe.js) | | |
8485
| [Permutations With Duplicates ](/LeetcodeProblems/Algorithms/Permutations_With_Duplicates.js) | | |

0 commit comments

Comments
 (0)