Last active
April 7, 2019 17:06
-
-
Save ZackFox/9c2afeb0ae7f5ed01401c831668f054e 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
// ключевой принцип | |
// prefix иницилизирован как первое слово | |
// сравнение символов из prefix с символами каждого слова слова | |
// если символ не совпадает - перезаписываем префикс и продолжаем | |
function longestCommonPrefix(strs) { | |
if(!strs || strs.length === 0 ) return ""; | |
let prefix = strs[0]; | |
for(let j = 1; j < strs.length; j++){ | |
const word = strs[j]; | |
for(let i = 0; i < prefix.length; i++){ | |
if(prefix === "") break; | |
if( i === prefix.length || i === word.length || prefix.charAt(i) !== word.charAt(i)){ | |
prefix = prefix.slice(0,i); | |
} | |
} | |
} | |
return prefix; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment