Ruby 方法来检查字符串回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8462512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:28:05  来源:igfitidea点击:

Ruby way to Check for string palindrome

ruby-on-railsrubystringruby-on-rails-3

提问by Mithun Sasidharan

I wanted to check if a string is palindrome or not using ruby code.

我想检查一个字符串是否是回文或不使用 ruby​​ 代码。

I am a starter in ruby so not too aquainted with the string methodsin ruby

我是 ruby​​ 的初学者,所以不太熟悉string methodsruby

回答by Michael Kohl

If you are not acquainted with Ruby's Stringmethods, you should have a look at the documentation, it's very good. Mithun's answer already showed you the basic principle, but since you are new to Ruby, there's a couple more things to keep in mind:

如果你不熟悉 Ruby 的String方法,你应该看看文档,它非常好。Mithun 的回答已经向您展示了基本原则,但是由于您是 Ruby 的新手,因此还有几件事需要牢记:

*) If you have a predicate method, it's customary to name it with a trailing question mark, e.g. palindrome?.

*) 如果您有谓词方法,习惯上用尾随问号命名它,例如palindrome?.

*) Boolean expressions evaluate to a boolean, so you don't need to explicitly return trueor false. Hence a short idiomatic version would be

*) 布尔表达式计算为布尔值,因此您无需显式返回trueor false。因此,一个简短的惯用版本将是

def palindrome?(str)
  str == str.reverse
end

*) Since Ruby's classes are open, you could add this to the string class:

*) 由于 Ruby 的类是开放的,您可以将其添加到字符串类中:

class String
  def palindrome?
    self == self.reverse
  end
end

*) If you don't want to monkey-patch String, you can directly define the method on single object (or use a module and Object#extend):

*) 如果你不想猴子补丁String,你可以直接在单个对象上定义方法(或使用模块和Object#extend):

foo = "racecar"
def foo.palindrome?
  self == self.reverse
end

*) You might want to make the palindrome check a bit more complex, e.g. when it comes to case or whitespace, so you are also able to detect palindromic sentences, capitalized words like "Racecar" etc.

*) 您可能想让回文检查更复杂一些,例如,当涉及到大小写或空格时,您还可以检测回文句子、大写单词,如“Racecar”等。

pal = "Never a foot too far, even."
class String
  def palindrome?
    letters = self.downcase.scan(/\w/)
    letters == letters.reverse
  end
end
pal.palindrome? #=> true

回答by Mithun Sasidharan

def check_palindromic(variable)
  if variable.reverse == variable #Check if string same when reversed 
    puts "#{ variable } is a palindrome."
  else # If string is not the same when reversed
    puts "#{ variable } is not a palindrome."
  end
end

回答by Powers

The recursive solution shows how strings can be indexed in Ruby:

递归解决方案展示了如何在 Ruby 中索引字符串:

def palindrome?(string)
  if string.length == 1 || string.length == 0
    true
  else
    if string[0] == string[-1]
      palindrome?(string[1..-2])
    else
      false
    end
  end
end

If reading the Ruby string documentation is too boring for you, try playing around with the Ruby practice questions on CodeQuizzesand you will pick up most of the important methods.

如果阅读 Ruby 字符串文档对您来说太无聊,请尝试在CodeQuizzes上玩 Ruby 练习题,您将掌握大部分重要方法。

回答by A H K

def is_palindrome(value)
 value.downcase!

 # Reverse the string
 reversed = ""
 count = value.length

 while count > 0
  count -= 1
  reversed += value[count]
 end
# Instead of writing codes for reverse string
# we can also use reverse ruby method
# something like this value == value.reverse  
if value == reversed
  return "#{value} is a palindrom"
 else
  return "#{value} is not a palindrom"
 end
end

puts "Enter a Word"
a = gets.chomp
p is_palindrome(a)

回答by Josh Brody

class String
  def palindrome?
    self.downcase == self.reverse.downcase
  end
end

puts "racecar".palindrome? # true
puts "Racecar".palindrome? # true 
puts "mississippi".palindrome? # false 

回答by Velusamy Venkatraman

> first method
a= "malayalam"
  if a == a.reverse
    puts "a is true"
  else
    puts "false"
  end

> second one
a= "malayalam"
a=a.split("")
i=0
ans=[]
  a.count.times do
    i=i+1
      k=a[-(i)]
      ans << k
    end
  if a== ans
      puts "true"
  else
      puts "false"
  end

回答by fossegrim

def palindrome?(string)
  string[0] == string[-1] && (string.length <= 2 || palindrome?(string[1..-2]))
end

回答by enowmbi

Solution 1Time complexity = O(n), Space complexity = O(n) This solution does not use the reverse method of the String class. It uses a stack(we could use an array that only allows entry and exit of elements from one end to mimic a stack).

方案一时间复杂度=O(n),空间复杂度=O(n) 这个方案没有使用String类的逆向方法。它使用一个堆栈(我们可以使用一个只允许元素从一端进入和退出的数组来模拟堆栈)。

def is_palindrome(str)
    stack = []
    reversed_str = ''
    str.each_char do |char|
        stack << char
    end
    until stack.empty?
       reversed_str += stack.pop 
    end
    if reversed_str == str
        return true
    else
        return false
    end
end


**Solution 2:**  Time complexity = O(n), Space complexity = O(1)

    def inplace_reversal!(str)
        i =0
        j = str.length - 1
        while i < j
          temp = str[i]
          str[i] = str[j]
          str[j] = temp
          i+=1
          j-=1
        end
        return str
      end

回答by Piyush Sawaria

str= gets.chomp 
str_rev=""
n=1
while str.length >=n
    str_rev+=str[-n]
    n+=1
end

if str_rev==str
    puts "YES"
else
    puts "NO"
end