How to find palindrome strings in Ruby
A palindrome is a sequence of characters that reads the same forward and backward.
For example, "madam" and "civic" are palindromic strings, while "programmer" is not. Palindromes are more than just a linguistic curiosity; they have practical applications in computer science and mathematics. Detecting palindromes is often a foundational problem in string manipulation, but it is useful for understanding more complex algorithms in areas such as natural language processing, DNA sequencing, and data compression.
Recognizing palindromes can also help optimize certain search algorithms and validate input against specific patterns, making it a valuable concept in both theoretical and applied computing.
Algorithm
To determine if a string is a palindrome in Ruby, we will create a function named is_palindrome?. This function takes a string as input and returns true if the string is a palindrome and false otherwise.
Steps
Let’s look at how it works step-by-step:
Input:
Take a string as input that needs to be checked for palindrome property.
Comparison:
Compare the characters from the beginning and the end of the string.
Iterate through the string, comparing corresponding characters until reaching the middle.
Result:
If all the characters match during the comparison, the string is a palindrome.
If any pair of characters does not match, the string is not a palindrome.
Code
The following code checks whether a given string is a palindrome or not.
def is_palindrome?(str)# Input: Take a string as input that needs to be checked for palindrome property.cleaned_str = str.downcase.gsub(/\W/, '') # Clean the string (lowercase, remove non-alphanumeric)# Comparison: Compare the characters from the beginning and the end of the string.# Iterate through the string, comparing corresponding characters until reaching the middle.left, right = 0, cleaned_str.length - 1while left < rightif cleaned_str[left] != cleaned_str[right]return falseendleft += 1right -= 1endtrueend# Example Usage:puts is_palindrome?("madam")puts is_palindrome?("programmer")puts is_palindrome?("HelloWorld!")
Explanation
Here is the explanation of the above coding example:
Line 1: Defines a method named
is_palindrome?that takes a string (str) as its parameter.Line 3: Creates a variable
cleaned_strby downcasing the input and removing non-alphanumeric characters using a regular expression (/\W/). This ensures consistent comparison.Line 7: Initializes two pointers,
leftandright, at the beginning and end ofcleaned_str.Lines 9–16: Runs a
whileloop as long asleftis less thanright. It compares characters at theleftandrightIndexes. If any mismatch is found, the method returnsfalse. Otherwise, the pointers move inward with each iteration.Line 17: If the loop completes without returning
false, the method returnstrue, confirming the string is a palindrome.Lines 21–23: Demonstrates the method with various input strings. One example includes spaces and punctuation, showcasing how the cleaning step ensures accurate results.
So, we have successfully implemented a robust and practical solution for finding palindromes in Ruby strings.
You can also find palindromes in other languages such as Python, Java, C++, etc.
Free Resources