标签:com elf etc 要求 sof 可迭代对象 soft 字符串数组 list
@author: ZZQ
@software: PyCharm
@file: longestCommonPrefix.py
@time: 2018/9/16 17:50
要求:查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""
e.g.: 输入: ["flower","flow","flight"] 输出: "fl"
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
class Solution():
def __init__(self):
pass
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
list_len = len(strs)
if list_len > 1:
str_len = min(len(f) for f in strs)
longest_substr = ""
for j in range(0, str_len):
c = strs[0][j]
index = 0
for i in range(1, list_len):
if c == strs[i][j]:
index += 1
print strs[i][j]
if index == (list_len-1):
longest_substr += c
else:
return longest_substr
return longest_substr
else:
if list_len == 1:
return strs[0]
else:
return ""
def longestCommonPrefix2(self, strs):
res = ""
if len(strs) == 0:
return ""
# zip()函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
for each in zip(*strs):
# print each # each 是由strs字符串列表中每一个对象的对应位置的元素组成的元祖。
# 利用集合创建一个无序不重复元素集
print(set(each))
if len(set(each)) == 1:
res += each[0]
else:
return res
return res
if __name__ == "__main__":
strs = ["dog", "racecar", "car"]
strs = ["flower", "flow", "flight"]
# strs = ["dog"]
# strs = ["aca", "cba"]
answer = Solution()
print answer.longestCommonPrefix2(strs)
标签:com elf etc 要求 sof 可迭代对象 soft 字符串数组 list
原文地址:https://www.cnblogs.com/zzq-123456/p/9671332.html