前言:最近在leetcode上刷题,感觉倍棒!然后,在写好程序之后,调用程序的时候,不小心造成了如下bug:
存在问题:TypeError: longestCommonPrefix() missing 1 required positional argument: 'strs'
分析问题:在我们定义函数和类的时候,在第一个参数的位置默认应该添加self,例如add(self,str,str1),然后我们在调用的时候应该首先实例化这个类,如Add().add('aaa'),而非直接调用Add.add('aaa')。
解决方法:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
res = ''
for i in range(len(strs[0])):
for j in range(1, len(strs)):
if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
return res
res += strs[0][i]
return res
b = ["flower","flow","flight"]
#a = Solution.longestCommonPrefix(b) #错误表达
a = Solution().longestCommonPrefix(b)
print(a)