原题:https://leetcode.com/problems/longest-common-prefix/
题意:
返回一个所有元素都是字符串的列表中所有字符串的共同前缀
思路:
首先假设第一个词整个是一个共同前缀,然后将它整体和第二个词与前缀等长部分比较,只要不同就把result剔除一位,一直到到相同为止;然后再继续将前缀与第三个词比较,一直进行;如果中间前缀result已经成为了空字符串,则直接输出空字符串
代码:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
result = strs[0]
i = 1
while i < len(strs):
if result == strs[i][0:len(result)]:
i += 1
else:
result = result[0:-1]
if result == '':
break
return result
结果:
Runtime:16 ms, faster than100.00%of Python online submissions for Longest Common Prefix.
Memory Usage:10.8 MB, less than78.73%of Python online submissions for Longest Common Prefix.
网友评论