<p>我使用python来解决leetcode中的“最长公共前缀”问题。这是我的代码:</p>
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(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
</code></pre>
<p>我用PyCharm做了些测试,没关系。
但当我在leetcode运行它时
它给了我:</p>
<p><strong>运行时错误消息:第52行:AttributeError:“list”对象没有属性“clear”
上次执行的输入:[“a”,“b”]</strong></p>
<p>第52行是:</p>
^{pr2}$
<p>我是新手,谢谢你的帮助!谢谢!在</p>