Longest Common Prefix
Question
Write a function to find the longest common prefix string amongst an array of strings.
Tags
- String
Thought
The algorithm is straightforward and the time complexity is O(mn).
Code
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
result = strs[0]
for item in strs[1:]:
for i in xrange(len(result)):
if i == len(item) or result[i] != item[i]:
result = result[:i]
break
return result