Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created August 12, 2015 06:24
Show Gist options
  • Select an option

  • Save viveksyngh/babe26924f1dddc09821 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/babe26924f1dddc09821 to your computer and use it in GitHub Desktop.
Longest Common Prefix in a array of Strings
__author__ = 'Vivek'
#LCP LONGEST COMMON PREFIX
def longestCommonPrefix(A):
"""
Find the longest common prefix in an array of string
:param: Array of strings
:return: prefix string
"""
prevLCP = A[0]
for i in range(1, len(A)):
curLCP = ""
j = 0
while (j < len(A[i]) and j < len(prevLCP)) and prevLCP[j] == A[i][j] :
curLCP += A[i][j]
j = j + 1
prevLCP = curLCP
return prevLCP
print(longestCommonPrefix("aaa", "aaaaaaabbbb", "aaaaaabbbbb")) # Will Return "aaa"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment