1

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

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>'
4

2 回答 2

4

String 的 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
于 2012-10-14T02:25:09.580 回答
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
于 2013-05-02T00:48:14.857 回答