题目链接在这里:最长公共前缀
虽然是很简单的模拟题,但是鼠鼠学习了很多面向对象编程中遇到的一些问题,具体的可以看这个链接python中的静态方法与实例方法
class Solution:
def longestCommonPrefix(self,strs)->str:
if not strs:
return ""
prefix,cnt = strs[0],len(strs)
for i in range(cnt):
prefix = self.lcp(prefix,strs[i])
if not prefix:
break
return prefix
def lcp(self,str1,str2)->str:
length,index = min(len(str1),len(str2)),0
while index<length and str1[index]==str2[index]:
index+=1
return str1[:index]
if __name__=="__main__":
s=["fuck","fudd","fuwe"]
ans=Solution().longestCommonPrefix(strs=s)
print(ans)
# class Solution:
# # 静态方法只能调用静态方法,或者用@classmethod和@context
# @staticmethod
# def longestCommonPrefix(strs)->str:
# if not strs:
# return ""
# prefix,cnt = strs[0],len(strs)
# for i in range(cnt):
# prefix = Solution.lcp(prefix,strs[i])
# if not prefix:
# break
# return prefix
# @staticmethod
# def lcp(str1,str2)->str:
# length,index = min(len(str1),len(str2)),0
# while index<length and str1[index]==str2[index]:
# index+=1
# return str1[:index]
# if __name__=="__main__":
# s=["fuck","fudd","fuwe"]
# ans=Solution.longestCommonPrefix(strs=s)
# print(ans)
标签:cnt,return,前缀,strs,str2,len,prefix,Leetcode,14
From: https://www.cnblogs.com/keximeiruguo/p/17241598.html