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"

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-09-27
  • 2021-10-13
猜你喜欢
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
  • 2021-10-27
  • 2021-09-17
相关资源
相似解决方案