码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] Longest Common Prefix @ Python

时间:2014-10-14 00:46:47      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   strong   sp   

Source: https://oj.leetcode.com/problems/longest-common-prefix/

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

Hint:   strs=[‘abc‘,‘ab‘,‘a‘]

strs=[

‘abc‘,

‘ab‘,

‘a‘,

]

We can think of strs as a column length varied matrix

 

 

class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        #横向扫描,每个字符串与第0 个字符串,从左到右比较,直到遇到一个不匹配,
        #然后继续下一个字符串
        #时间复杂度O(n1+n2+...)
        if len(strs) == 0: return ""
        minL = min([len(word) for word in strs])
        for j in range(minL):
            for i in range(1, len(strs)):
                if strs[i][j] != strs[0][j]:
                    return strs[0][:j]
        return strs[0][:minL]

 

[leetcode] Longest Common Prefix @ Python

标签:style   blog   http   color   io   ar   for   strong   sp   

原文地址:http://www.cnblogs.com/asrman/p/4023257.html

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