我使用python来解决leetcode中的“最长公共前缀”问题。这是我的代码:
class Solution:
# @param {string[]} strs
# @return {string}
def longestCommonPrefix(self, strs):
if strs is None or strs == []:
return ""
if "" in strs:
return ""
minList=[]
tempList=[]
prefix=""
if len(strs)>0:
minLen = len(strs[0])
for str in strs:
if len(str)<minLen:
minLen = len(str)
for str in strs:
if len(str)==minLen:
minList.append(str)
if len(minList)==1:
prefix = minList[0]
else:
while True:
isAllEqual = True
for min in minList:
if min!=minList[0]:
isAllEqual=False
if isAllEqual:
prefix=minList[0]
break
else:
for min in minList:
tempList.append(min[:-1])
minList.clear()
minList=tempList.copy()
tempList.clear()
if prefix == "":
return prefix
for string in strs:
if prefix in string:
continue
else:
while prefix:
prefix = prefix[:-1]
if prefix =="":
return ""
if prefix in string:
break
return prefix
我用PyCharm做了些测试,没关系。 但当我在leetcode运行它时 它给了我:
运行时错误消息:第52行:AttributeError:“list”对象没有属性“clear” 上次执行的输入:[“a”,“b”]
第52行是:
^{pr2}$我是新手,谢谢你的帮助!谢谢!在
您正在使用python2解释器来运行这段代码,这是python3代码。有几种解决方法。 你可以使用一个shebang line像
或者在终端中调用python3解释器。像
^{pr2}$python3
list
类有一个clear()
方法,但python2list
类没有。这很可能是问题的根源。leetcode似乎将使用python2运行脚本,因此您应该在python2中开发它,以避免类似这样的不兼容。在相关问题 更多 >
编程相关推荐