Search code examples
rubystringalgorithmpalindrome

Palindrome count in a string


So, I explored www.hackerearth.com today and was solving my first problem statement in ruby: http://www.hackerearth.com/problem/algorithm/palindrome-count-1/

Palindrome count Problem:

Given a string S, count the number of non empty sub strings that are palindromes. A sub string is any continuous sequence of characters in the string. A string is said to be palindrome, if the reverse of the string is same as itself. Two sub strings are different if they occur at different positions in S

Input: Input contains only a single line that contains string S.

Output: Print a single number, the number of sub strings that are palindromes.

Constraints

1 <= |S| <= 50

S contains only lower case latin letters, that is characters a to z.

Sample Input (Plaintext Link): dskjkd
Sample Output (Plaintext Link): 7

Explanation -

The 7 sub strings are d, s, k, j, k, d, kjk.

Time limit 3 sec(s)

Memory limit 256 MB

Source limit 1024 KB

Here is what I did:

chars = gets.chomp.gsub(' ', '').split('')
counts = chars.count
(2..chars.count).each do |len|
  chars.combination(len).each do |comb|
    string = comb.inject(:<<)
    counts += 1 if string.reverse == string
  end
end
puts counts

However, this approach seems to be inefficient in terms of the time execution and memory usage. Is there any way to optimize this? Or have any other approach to this solution, algorithm is also welcome as solution! Thanks.

Edit

Since, all the answers are correct. I had to choose the one which is efficient. So, I ran benchmark and here is the result: https://gist.github.com/suryart/7577481

Based on the result you can see this answer is much faster. Thank you for the new approaches/ solution guys! :)


Solution

  • using the algorithm to get all subsets of the string from What is the best way to split a string to get all the substrings by Ruby?

    count = 0
    
    (0..len-1).each do |i|
      (i..len-1).each do |j|
        temp = s[i..j]
        count = count + 1 if temp == temp.reverse
      end
    end
    puts "found #{count} palindromes"