Longest Common Prefix
(LeetCode Problems)
Problem:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"] Output: "fl" |
Example 2:
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. |
Constraints:
SOLUTION:
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { if(strs.length == 1) { return strs[0] } let shortName = strs.sort((a,b) => a.length-b.length)[0]; let common = ""; for(let i=0;i<shortName.length;i++) { let hasLetter = false; for(let j=0;j<strs.length;j++){ if(shortName[i] != strs[j][i]) { return common; } else { hasLetter = true } } if(hasLetter) { common += shortName[i]; } } return common ? common : ""; }; |
Explanation:
strs is an array and is input value.
Step 1:
if(strs.length == 1) { return strs[0] } /* * if strs has only one input then that value will result as output. */ |
Step 2:
/* *Longest common prefix will also be the shortest length string in an array. So, let's find out the *shortest item first. */
let shortName = strs.sort((a,b) => a.length-b.length)[0]; |
Step 3:
/* *Now create a variable common as an empty string. */
let common = "";
/* Now check every string starting from position 0, if found in every item concat string and continue else exit from the loop. */
for(let i=0;i<shortName.length;i++) { let hasLetter = false; for(let j=0;j<strs.length;j++){ if(shortName[i] != strs[j][i]) { return common; } else { hasLetter = true } } if(hasLetter) { common += shortName[i]; } } // finally return the common string |
Here is the link to the original question.