这是一个测试文件 👇👇👇👇👇👇👇
class String
def palindrome?
# ...
end
end
"madam".palindrome? # => true
"racecar".palindrome? # => true
"madam, . ".palindrome? # => true
"02/02/2020".palindrome? # => true
"11/11/11 11:11".palindrome? # => true
"Madam, I'm Adam".palindrome? # => true
"A man, a plan, a canal – Panama".palindrome? # => true
大家都来说下自己的💡💡想法💡💡,分享到下方的回复中
这是我的版本,欢迎大家指教👉👉👉https://gist.github.com/mehdi-farsi/2729f421c0d408552cf22adab45a0ca8
class String
def palindrome?
mid_index = self.size/2
mid_index.times do |i|
return false if self[i]!=self[self.size-1-i]
end
true
end
end
p "1234321".palindrome? # true
p "123321".palindrome? # true
p "122321".palindrome? # false
p "223321".palindrome? # false
轴对称,非常棒的方式。但是不全面,例如"A man, a plan, a canal – Panama".palindrome?就是个例子 请看下我的方式,https://gist.github.com/mehdi-farsi/2729f421c0d408552cf22adab45a0ca8feel,当然你还有别的方式,也请 free 留言,谢谢。
String 本身就是一个回文字符串,可以包含标点,空格。 例如"A man, a plan, a canal – Panama" 反过来就是👉👉👉“Amanap lanac a nalP a nam a”
class String
def palindrome?
self.reverse == self
end
end
p "1234321".palindrome? # true
p "123321".palindrome? # true
p "122321".palindrome? # false
p "223321".palindrome? # false
class String
def palindrome?
self.reverse == self
end
end
p "1234321".palindrome? # true
p "123321".palindrome? # true
p "122321".palindrome? # false
p "223321".palindrome? # false
p "11/11/11 11:11".palindrome? # false. 应该是true
p "A man, a plan, a canal – Panama".palindrome? # false. 应该是true
class String
def palindrome?
a=self.gsub(/[^\w]/,'').upcase
a.reverse == a
end
end
p "1234321".palindrome? # true
p "123321".palindrome? # true
p "122321".palindrome? # false
p "223321".palindrome? # false
p "11/11/11 11:11".palindrome? # false. 应该是true
p "A man, a plan, a canal – Panama".palindrome? # false. 应该是true
Michael Hartl 在去年的 RubyConf 上以这个例子做过分享
class String
def palindrome?
return false if empty?
letters = scan(/[a-zA-Z0-9]/).join.downcase
letters == letters.reverse
end
end