Categories
Array Leetcode String

Longest Common Prefix

let longestCommonPrefix = function(strs) {

if (!strs.length) return '';

let index = 0, curr = '';
for (;;)
{
for (let i = 0; i < strs.length; i++) {
if (strs[i].length <= index) {
return strs[0].substring(0, index); //?
}
if (curr === '') curr = strs[i][index];
if (curr !== strs[i][index]) {
return strs[0].substring(0, index);
}
if (i === strs.length - 1) {
curr = '';
index++
}
}
}

return '';
};

Leave a Reply

Your email address will not be published. Required fields are marked *