回顾红宝石的回文

时间:2012-10-14 02:20:32

标签: ruby

为什么此代码为此输入提供了错误的输出?

def palindrome?(str)
   str.delete('^a-zA-Z')
   str.downcase 
   str == str.reverse
end


INPUT = "A man, a plan, a canal -- Panama"

OUTPUT = Failure/Error: palindrome?("A man, a plan, a canal -- Panama").should be_true, "Incorrect results for input: \"A man, a plan, a canal -- Panama\""
      Incorrect results for input: "A man, a plan, a canal -- Panama"
    # spec.rb:7:in `block (2 levels) in <top (required)>'
    # ./lib/rspec_runner.rb:36:in `block in run_rspec'
    # ./lib/rspec_runner.rb:32:in `run_rspec'
    # ./lib/rspec_runner.rb:23:in `run'
    # lib/graders/weighted_rspec_grader.rb:6:in `grade!'
    # ./grade:31:in `<main>'

2 个答案:

答案 0 :(得分:4)

Strings上的delete和downcase方法不会修改String本身,它们会返回更改的副本。如果要修改接收器,请使用bang变体:

str.delete!('[^a-zA-Z]')
str.downcase!

第二个想法,不要这样做,因为这样的可怕事情发生了:

string = "hello123"
palindrome?(string)
string    #=> "OLLEH"

相反,复制一下参数并修改它:

def palindrome?(arg)
  str = arg.dup
  str.delete!('[^a-zA-Z]')
  str.downcase!
  str == str.reverse
end

答案 1 :(得分:0)

如何查找字符串的回文总数

class String 
  def palindrome?
    self == self.strip.reverse
  end
  def sub_str_arr
    (0..self.length).inject([]){|ai,i|
      (1..self.length - i).inject(ai){|aj,j|
        aj << self[i,j]
      }
    }
  end
  def num_palindromes
    return -1 if self.length > 100000000
    self.sub_str_arr.reject!{|item| item if item.length < 2 || !item.palindrome?}.size
  end
end

puts "dabadbadbadbdbadbadbdabdbadbadbadbadbadadadbdbdbdbadbdabadbadbdbadbabdabdbbdabdabdbadba".num_palindromes