今天的题目是14. 最长公共前缀
乍看题目不难,难度也是简单,先弄了一个纯暴力解法。再去看好的题解。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# 前缀
pre = ''
# 如果长度为空直接返回
if len(strs) == 0:return pre
# 遍历第一个字符串
for s in strs[0]:
# 前缀加上当前循环字母
pre += s
# 遍历数组剩余字符串
for j in range(1, len(strs)):
# 如果后续字符串不以当前前缀开头,则返回上一次符合所有的前缀
if not strs[j].startswith(pre):
return pre[:-1]
# 返回前缀
return pre
执行用时 :44 ms, 在所有 Python3 提交中击败了35.93%的用户
内存消耗 :13.3 MB, 在所有 Python3 提交中击败了5.14%的用户
看了题解号称超级快的方法,好像也没快,不知道什么情况
if not strs: return ""
s1 = min(strs)
s2 = max(strs)
for i,x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1
执行用时 :40 ms, 在所有 Python3 提交中击败了52.32%的用户
内存消耗 :
13.6 MB, 在所有 Python3 提交中击败了5.14%的用户
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
return os.path.commonprefix(strs)
执行用时 :44 ms, 在所有 Python3 提交中击败了35.93%的用户
内存消耗 :13.4 MB, 在所有 Python3 提交中击败了5.14%的用户
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
#zip(*str) set
res=""
# print(zip(*strs))
for i in zip(*strs):
# print(i)
if len(set(i))==1:
res+=i[0]
else:
break
return res
执行用时 :52 ms, 在所有 Python3 提交中击败了19.18%的用户
内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.14%的用户