Non-recursive
def is_palindrome(s)Recursive
s == s.reverse
end
def is_palindrome_r(s)Testing Note that the recursive method is much slower -- using the 2151 character palindrome by Dan Hoey here, we have:
if s.length <= 1
true
elsif s[0] != s[-1]
false
else
is_palindrome_r(s[1..-2])
end
end
str = "A man, a plan, a caret, [...2110 chars deleted...] a canal--Panama.".downcase.delete('^a-z')output
puts is_palindrome(str) # => true
puts is_palindrome_r(str) # => true
require 'benchmark'
Benchmark.bm do |b|
b.report('iterative') {10000.times {is_palindrome(str)}}
b.report('recursive') {10000.times {is_palindrome_r(str)}}
end
true
true
user system total real
iterative 0.062000 0.000000 0.062000 ( 0.055000)
recursive 16.516000 0.000000 16.516000 ( 16.562000)
No comments:
Post a Comment