0 Replies - 1319 Views - Last Post: 11 November 2009 - 02:07 PM

#1 EdwinNameless   User is offline

  • D.I.C Addict
  • member icon

Reputation: 128
  • View blog
  • Posts: 723
  • Joined: 15-October 09

Palindrome using a stack

Posted 11 November 2009 - 02:07 PM

Description: This script indicates whether a string is a palindrome or not (without taking into account whitespaces or punctuation) using a stack. Obviously, there is a much simpler solution by just reversing the string:
input = gets.chomp
puts (input.reverse == input ? "palindrome": "not palindrome")

But where is the fun in that?
def palindrome?(input)
  stack = []
  output = ""
  input.each_char{|x| stack.push x}
  while not stack.empty?
    output << stack.pop
  end
  output == input
end

input = gets.chomp
puts (palindrome?(input) ? "palindrome": "not palindrome")



Is This A Good Question/Topic? 0
  • +

Page 1 of 1