Skip to content

Instantly share code, notes, and snippets.

@jones
Created December 31, 2014 06:25
Show Gist options
  • Save jones/bb9c32cb7b35dd80a626 to your computer and use it in GitHub Desktop.
Save jones/bb9c32cb7b35dd80a626 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
# computes the LCP of the stringlist strs
if strs is None or len(strs) == 0:
return ""
return reduce(self.lcp, strs)
def lcp(self, str1, str2):
# computes the LCP of str1 and str2
for index, (char1, char2) in enumerate(zip(str1, str2)):
if char1 != char2:
return str1[:index]
return str1[:min(len(str1), len(str2))]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment