Last active
October 19, 2022 09:33
-
-
Save OlegKorn/65f32f15a670b84d30fa9e7f0633256e to your computer and use it in GitHub Desktop.
leetcode longestCommonPrefix - https://leetcode.com/problems/longest-common-prefix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a function to find the longest common prefix | |
string amongst an array of strings. | |
If there is no common prefix, return an empty string "". | |
Example 1: | |
Input: strs = ["flower","flow","flight"] | |
Output: "fl" | |
Example 2: | |
Input: strs = ["dog","racecar","car"] | |
Output: "" | |
Explanation: There is no common prefix among the input strings. | |
Constraints: | |
1 <= strs.length <= 200 | |
0 <= strs[i].length <= 200 | |
strs[i] consists of only lowercase English letters. | |
*/ | |
var longestCommonPrefix = function(strs) { | |
// sort by abc | |
strs = strs.sort(function(a, b) { return (a > b ? 1 : (a === b ? 0 : -1)) }) | |
const allEqual = arr => arr.every(val => val === arr[0]) | |
var isAllEqual = allEqual(strs) | |
if (isAllEqual) { | |
return strs[0] | |
} | |
if (strs.length === 1) { | |
return strs[0] | |
} | |
var shortestWord = strs.reduce(function(a, b) { return a.length <= b.length ? a : b }) | |
var shortestWordLen = shortestWord.length | |
var shortestWordFirstLetter = shortestWord[0] | |
if (shortestWordLen === 1) { | |
shortestWordLen += 1 | |
} | |
if (strs.length === 2) { | |
if (strs[0] == "" && strs[1] == "") { | |
return "" | |
} | |
if (!strs[1].startsWith(strs[0][0])) { | |
return "" | |
} | |
} | |
var solution = "" | |
for (var i = 0; i <= shortestWordLen; i++) { | |
if (i === 0) { | |
key = strs[0].slice(0, 1) | |
} | |
else { | |
key = strs[0].slice(0, i) | |
} | |
for (var j = 0; j < strs.length; j++) { | |
if (strs[j].startsWith(key)) { | |
continue | |
} | |
if (!strs[j].startsWith(key)) { | |
return solution | |
} | |
} | |
solution = key | |
} | |
return solution | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment