[LeetCode]14_Longest Common Prefix

Posted PrConstantin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]14_Longest Common Prefix相关的知识,希望对你有一定的参考价值。

Write a function to find the longest common prefix string amongst an array of strings.

寻找最长公共前缀


let longestCommonPrefix = (strs)=>
    if(strs[0]===undefined)
        return ''
    
   let ans = []
   for(let i=0;i<strs[0].length;i++)
       let _char = strs[0][i]
       let tag = true
        for(let j=0;j<strs.length;j++)
            if(_char !== strs[j][i])
                tag = false
            
        
        if(tag)
            ans.push(_char)
        else
            break
        
   
   return ans.join('')


console.log(longestCommonPrefix(['123','12']))
console.log(longestCommonPrefix([]))
console.log(longestCommonPrefix(['123123']))
console.log(longestCommonPrefix(['123123','12']))

以上是关于[LeetCode]14_Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

leet_14 Longest Common Prefix

14. Longest Common Prefix

#Leetcode# 14. Longest Common Prefix

LeetCode OJ 14Longest Common Prefix

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix