Created
August 12, 2015 06:24
-
-
Save viveksyngh/babe26924f1dddc09821 to your computer and use it in GitHub Desktop.
Longest Common Prefix in a array of Strings
This file contains hidden or 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
| __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