Created
August 4, 2019 07:52
-
-
Save ArataKagan/cec6395e7b8fe74bbc9cb4274c4337d0 to your computer and use it in GitHub Desktop.
This file contains 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
var longestCommonPrefix = function(strs) { | |
var common = ""; | |
var index = 0; | |
if(strs.length == 0 || strs == "null"){ | |
return common; | |
} | |
// split the first string of strs | |
var string = strs[0].split(""); | |
// Loop over the stored string's letter | |
for(let i=0; string.length > i; i++){ | |
var letter = string[i]; | |
// Loop over the rest of the strings and compare the same indexies of each string | |
for(let j=1; strs.length > j; j++){ | |
if(letter != strs[j].charAt(index) || index > strs[j].length){ | |
return common; | |
} | |
} | |
common += letter; | |
index++; | |
} | |
return common; | |
}; | |
longestCommonPrefix(["flower","flow","flight"]) // return "fl" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Coding practice from Leet Code's "Longest Common Prefix" question.