编写一个函数来查找字符串数组中的最长公共前缀。
function longestCommonPrefix2(strs){ if(!strs || strs.length == 0){ return '' } var temp = strs[0] for(var i=0;i<strs.length;i++){ var j = 0; for(;j<strs[i].length && j<temp.length;j++){ if(temp.charAt(j) !== strs[i].charAt(j)){ break; } } temp = temp.substring(0,j) } return temp; } longestCommonPrefix2(["flower","flow","flight"]) // 输出 "fl"
方法二:
//输入 ["flower","flow","flight"] function longestCommonPrefix2(strs){ if(!strs || strs.length == 0){ return '' } var temp = strs[0] for(var i =1;i<strs.length;i++){ while(strs[i].indexOf(temp) < 0){ temp = temp.substring(0,temp.length -1) } } return temp } longestCommonPrefix2(["flower","flow","flight"])
// 输出 "fl"