Created
November 26, 2018 13:58
-
-
Save aire-con-gas/2e3ab0ee55065af9179d2743fc2a22a7 to your computer and use it in GitHub Desktop.
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
/** | |
* @param {string[]} strs | |
* @return {string} | |
*/ | |
var longestCommonPrefix = function(strs) { | |
// initialize matches found map | |
var matchesFound = {}; | |
var commonPrefix = ''; | |
var lastMatchedPrefix; | |
var matchesFoundKeys; | |
if (strs.length === 1) { | |
return strs[0]; | |
} | |
var findCommonPrefix = function(word1, word2) { | |
var result = []; | |
var a = word1.split(''); | |
var b = word2.split(''); | |
for(var i = 0, il = a.length; i < il; i++) { | |
if (a[i] === b[i]) { | |
result.push(a[i]); | |
} else { | |
break; | |
} | |
} | |
return result.join(''); | |
}; | |
for (var i = 0, j = 1, il = strs.length; i < il && strs[j]; i++, j++) { | |
lastMatchedPrefix = findCommonPrefix(strs[i], strs[j]); | |
if (lastMatchedPrefix) { | |
matchesFound[lastMatchedPrefix] = (matchesFound[lastMatchedPrefix] || 0) + 1; | |
} | |
} | |
matchesFoundKeys = Object.keys(matchesFound); | |
if (matchesFoundKeys.length <= strs.length - 1 && matchesFoundKeys.length > 1) { | |
for (var i = 0, j = 1, il = matchesFoundKeys.length; i < il && matchesFoundKeys[j]; i++, j++) { | |
commonPrefix = findCommonPrefix(matchesFoundKeys[i], matchesFoundKeys[j]); | |
} | |
} else if (matchesFoundKeys.length === 1) { | |
commonPrefix = lastMatchedPrefix; | |
} | |
return commonPrefix; | |
// iterate through each word in the str array | |
// if a[i] === b[i] then add to result and keep checking | |
// else break and move onto the next word | |
// if matches found === strs.length - 1 && matches.found > 1 | |
// iterate again | |
// return match or empty string | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment