Skip to content

Instantly share code, notes, and snippets.

@ZackFox
Last active April 7, 2019 17:06
Show Gist options
  • Save ZackFox/9c2afeb0ae7f5ed01401c831668f054e to your computer and use it in GitHub Desktop.
Save ZackFox/9c2afeb0ae7f5ed01401c831668f054e to your computer and use it in GitHub Desktop.
// ключевой принцип
// 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