LeetCode mthods for longest common prefix on python3

Problem: To find the longest comman prefix amongest an array of strings.

               If no comman prefix, return " ".

以下是方法: 

'''

第一种方法:

排序将相同多的字符串排在一起,而相同部分少的要排到首尾两端

如果存在共同部分,一定会出现在首尾两端的字符串。

防止溢出出现,比较首尾两端长度,取较短进行遍历。

'''

'''

class Solution:

def longestCommonPrefix(self, s):

if s == None:

return ""

if len(s) == 1:

return s[0]

# 先将s所有string item 排序,这样所有string item就是从a-z的排列

sorted_s = sorted(s)

common = ''

for c in sorted_s[0]: # 从第一个stringitem开始检验最后一stringitem是否有相同项

if sorted_s[-1].startswith(common+c): # startswith的方法比较检验

common += c

else:

break

return common

'''

"""

# 第二种方法: 两重的遍历搜索

 

class Solution:

def longestCommonPrefix(self, s):

if s == None:

return ''

if len(s) == 1:

return s[0]

 

same = ' '

for i in range(len(s[0])):

c = s[0][i]

for j in range(1, len(s)):

if i >= len(s[j]) or s[j][i] != c:

return same

same += c

return same

"""

# 第三种方法

# 该方法使用min() 和 max(),他们返回是按照alphabetic order 进行筛选

# 利用enumerate方法遍历min部分,比较筛选出same part

class Solution:

def longestCommonPrefix(self, s):

if not s:

return ''

s1 = min(s)

s2 = max(s)

for i, c in enumerate(s1):

if c != s2[i]:

return s1[:i]


 

from datetime import datetime

if __name__ == "__main__":

t0 = datetime.now()

str1 = ["flower","flirht","flow"]

str2 = ["dog","cat","racer"]

testDemo1 = Solution().longestCommonPrefix(str1)

testDemo2 = Solution().longestCommonPrefix(str2)

t1 = datetime.now()

print("runtime: ",(t1-t0).microseconds)

print("common: fl ",testDemo1)

print(" No Common")

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值