Longest Common Prefix
Description
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: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
Solution(javascript)
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
function cmnPrefix(a, b){
let i = 0;
let p = '';
while (i < a.length && i < b.length){
if(a[i] === b[i]) {
p += a[i];
i++;
} else {
break;
}
}
return p;
}
function findCmnPrefix(strArr, prefix){
if(!strArr.length || !prefix.length)
return prefix;
return findCmnPrefix(strArr.splice(1, strArr.length), cmnPrefix(prefix, strArr[0]));
}
if(!strs || !strs.length) return '';
return findCmnPrefix(strs.splice(1, strs.length), strs[0]);
};