14. Longest Common Prefix
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
1 /** 2 * @param {string[]} strs 3 * @return {string} 4 */ 5 var longestCommonPrefix = function(strs) { 6 7 //每次都拿一个最长公共前序列去比较得了 比如string[] = ["aa","ab","ap"] 8 // aa 和 ab 比较是 a , 然后 a 和 ap 去比较 还是 a 9 10 function lcp(a,b){ 11 12 var min_len = Math.min(a.length,b.length); 13 var count = 0; 14 for(var i = 0; i< min_len;i++){ 15 if(a[i] == b[i]){ 16 count++; 17 }else{ 18 break; 19 } 20 } 21 22 return a.substr(0,count); 23 } 24 25 var slen = strs.length; 26 27 if(slen == 0){ 28 29 return ""; 30 } 31 32 if(slen == 1){ 33 return strs[0]; 34 } 35 36 var pattern = strs[0] 37 38 for(var i = 1; i<slen;i++){ 39 pattern = lcp(pattern,strs[i]); 40 } 41 42 return pattern; 43 };