Created
December 31, 2014 06:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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