码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 14 Longest Common Prefix

时间:2015-06-29 11:32:33      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

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

直接按第一个元素开始比较,最后截取符合要求的前段。

var longestCommonPrefix = function(strs) {
    if(strs.length===0) return ‘‘
    var c = strs[0]
    for(var i=1;i<strs.length;i++){
        var j = 0
        while(j<strs[i].length && j<c.length && strs[i][j]===c[j])
            j++
        c = c.slice(0,j)
    }
    return c
}

 

Leetcode 14 Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4606971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!