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

[leetcode]Longest Common Prefix @ Python

时间:2014-06-10 16:31:52      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

原题地址:https://oj.leetcode.com/problems/longest-common-prefix/

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

解题思路:找出所有字符串共同的前缀。

代码:

bubuko.com,布布扣
class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        if len( strs ) == 0:
            return ‘‘
        if len( strs ) == 1:
            return strs[0]
        minstrslen = 9999
        index = 0
        for i in range( 0, len( strs ) ):
            if len( strs[i] ) < minstrslen:
                minstrslen = len( strs[i] )
                index = i
        ShortestString = strs[index]
        list = [0 for i in range( len( ShortestString ) )]
        for i in range(0, len( ShortestString )):
            for j in range(0, len( strs )):
                if strs[j][i] == ShortestString[i]:
                    list[i] += 1
        Prefix = ‘‘
        for i in range(0, len( ShortestString )):
            if list[i] == len( strs ):
                Prefix += ShortestString[i]
            else:
                break
        return Prefix
bubuko.com,布布扣

 

[leetcode]Longest Common Prefix @ Python,布布扣,bubuko.com

[leetcode]Longest Common Prefix @ Python

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/zuoyuan/p/3779749.html

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