Ruby Palindrome Check
def is_palindrome?(str) return true if str.nil? || str.empty? # Clean the string: remove non-alphanumeric characters and convert to lowercase. cleaned_str = str.downcase.gsub(/[^a-z0-9]/, '') # Compare the cleaned string with its reverse. cleaned_str == cleaned_str.reverse end
This Ruby method determines if a given string is a palindrome, meaning it reads the same forwards and backward. It first cleans the input string by removing non-alphanumeric characters and converting it to lowercase, the...
The `is_palindrome?` method checks if a string reads the same forwards and backward. It handles `nil` or empty strings by returning `true`. The core logic involves cleaning the input string: it converts the string to lowercase using `downcase` and removes any characters that are not lowercase letters or digits using `gsub(/[^a-z0-9]/, '')`. This ensures that case and punctuation do not affect the palindrome check. Finally, it compares the `cleaned_str` with its reversed version (`cleaned_str.reverse`). If they are identical, the string is a palindrome, and the method returns `true`; otherwise, it returns `false`. The time complexity is dominated by the `gsub` and `reverse` operations, both of which are O(n), where n is the length of the string. The space complexity is O(n) due to the creation of the `cleaned_str` and its reversed copy.
function is_palindrome(input_string): if input_string is null or empty: return true initialize cleaned_string by converting input_string to lowercase and removing non-alphanumeric characters return cleaned_string is equa...