When the whole world is about to rain, let's make it clear in our heart together

热爱前端开发,专注于前端

编写一个函数来查找字符串数组中的最长公共前缀。

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"

 

posted @ 2022-02-11 11:29  婷风  阅读(132)  评论(0编辑  收藏  举报