Created
March 1, 2011 20:20
-
-
Save ashish0x90/849813 to your computer and use it in GitHub Desktop.
My solution for Greplin_problem_1 as a reply to this comment at HN - http://news.ycombinator.com/item?id=2276473
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
#Two algos for solving problem-1 at http://challenge.greplin.com/ | |
def getPalindrome1(text): | |
''' | |
A more effecient approach for finding palindromes : | |
Iterate through the text and, | |
Case1: | |
For each character, check if it forms MIDDLE character of a (ODD-LENGTH) palindrome. | |
For ex. Palindrome like rac[e]car, abc[d]cba | |
Case2: | |
For each character, check if it forms LEFT character of a (EVEN-LENGTH) palindrome. | |
For ex. Palindrome like ra[c]car, ab[c]cba | |
Worst case - O(n2), Average case - O(n). | |
''' | |
longestPalindrome='' | |
for idx in range(len(text)): | |
#Case1 consider idx'th chr as the middle character | |
cur=1 | |
max_word1,max_word2='','' | |
while cur <= min(idx,len(text)-idx-1) and text[idx-cur] == text[cur+idx]: | |
max_word1 = text[idx-cur:idx+cur+1] | |
cur+=1 | |
#Case2 consider idx'th chr as the left character | |
cur=0 | |
while cur <= min(idx,len(text)-idx-2) and text[idx-cur] == text[cur+idx+1]: | |
max_word2 = text[idx-cur:idx+cur+2] | |
cur+=1 | |
longestPalindrome = max([max_word2,max_word1,longestPalindrome], key=lambda x:len(x)) | |
return longestPalindrome | |
def getPalindrome2(text): | |
''' | |
Good'ol brute force solution to generate all possible strings and see if it's a palindrome (word and it's reverse form are | |
identical). | |
*The O(n2) solution will work for this case, as the text input is pretty small. | |
''' | |
longestPalindrome = '' | |
for i in range(len(text)): | |
for j in range(i, len(text)): | |
word = text[i:j] | |
if word == word[::-1]: | |
longestPalindrome = max([longestPalindrome, word], key=lambda x:len(x)) | |
return longestPalindrome |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment