[LeetCode]14_Longest Common Prefix

来源:互联网 发布:看漫画软件mangameeya 编辑:程序博客网 时间:2024/06/17 23:29

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']))
原创粉丝点击