Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var longestCommonPrefix = function(strs) {
- const firstWord = strs[0];
- const arrResults = [];
- let index = 1;
- let arrWithoutFirstElement = strs.slice(1, strs.length);
- if(strs.length===0)return '';
- if(strs.length===1)return strs[0];
- while(index <= firstWord.length) {
- if(arrWithoutFirstElement.every(element =>
- element.substring(0,index)===firstWord.substring(0,index))){
- arrResults.push(firstWord.substring(0,index));
- }
- index++;
- }
- return arrResults.length > 0 ? arrResults[arrResults.length-1] : '';
- }
- console.log(longestCommonPrefix(["flower","flow","flight"]));
Add Comment
Please, Sign In to add comment