samedi 25 avril 2015

longest palindrome in Ruby on Rails


Write a method that takes in a string of lowercase letters (no uppercase letters, no repeats). Consider the substrings of the string: consecutive sequences of letters contained inside the string. Find the longest such string of letters that is a palindrome.

Based on local method Palindrome?(string), I implemented longest-palindrome(string) as below with test cases:

def palindrome?(string)
  i = 0
  while i < string.length
    if string[i] != string[(string.length - 1) - i]
      return false
    end

    i += 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 are tests to check that your code is working. After writing
# your solution, they should all 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 as below:

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

Why did the second test failed?


Aucun commentaire:

Enregistrer un commentaire