LintCode Q78 Longest Common Prefix in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2016年12月18日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
# @param strs: A list of strings
# @return: The longest common prefix
def longestCommonPrefix(self, strs):
# write your code here
# time complexity: O(m*n)
# space complexity: O(1)
if str is None or len(strs) == 0 or len(strs[0]) == 0:
return ""
for i in xrange(len(strs[0])):
prefix = strs[0][i]
found = True
for j in xrange(1, len(strs)):
if i >= len(strs[j]) or strs[j][i] != prefix:
found = False
i -= 1
break
else:
continue
if not found:
break
else:
continue
return strs[0][:i+1]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。