longest palindrome in Ruby on Rails -


write method takes in string of lowercase letters (no uppercase letters, no repeats). consider substrings of string: consecutive sequences of letters contained inside string. find longest such string of letters palindrome.

based on local method palindrome?(string), implemented longest-palindrome(string) below test cases:

def palindrome?(string)   = 0   while < string.length     if string[i] != string[(string.length - 1) - i]       return false     end      += 1   end    return true end  def longest_palindrome(string)   dix = 0   lstr = ""   lstrc = nil   while dix < string.length     dix2 = 1     while dix2 < string.length       str = string.slice(dix,dix2)       count = str.length       if palindrome?(str)         if lstrc == nil || lstrc < count           lstr = str           lstrc = count         end       end       dix2 += 1     end     dix += 1   end   puts(lstr)   return lstr end  # these tests check code working. after writing # solution, should print true.  puts(   'longest_palindrome("abcbd") == "bcb": ' +   (longest_palindrome('abcbd') == 'bcb').to_s ) puts(   'longest_palindrome("abba") == "abba": ' +   (longest_palindrome('abba') == 'abba').to_s ) puts(   'longest_palindrome("abcbdeffe") == "effe": ' +   (longest_palindrome('abcbdeffe') == 'effe').to_s ) 

test results below:

bcb                                                                                                                                                                                     longest_palindrome("abcbd") == "bcb": true                                                                                                                                              bb                                                                                                                                                                                      longest_palindrome("abba") == "abba": false                                                                                                                                             effe                                                                                                                                                                                    longest_palindrome("abcbdeffe") == "effe": true   

why did second test failed?

... line preventing considering entire string

while dix2 < string.length 

so when dix whole string, you're not doing testing palindromes

change line to...

while dix2 <= string.length 

it more efficient if did...

while dix2 <= string.length - dix 

which prevent testing (for, say, string of length 10), string(7,3) , string(7,4) , string(7,5) etc. etc., same string.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -