How to find the last repeated character in a string with Ruby

1 Answer

0 votes
require 'set'

# Finds the last repeated character in a string.
# Scans the string from right to left using a Set to track seen characters.
# Returns the character, or nil if no characters are repeated.
def find_last_repeated_character(str)
  seen = Set.new

  # Iterate through the string's characters in reverse order (right to left)
  str.chars.reverse_each do |char|
    # Set#add? returns nil if the element is already present in the set.
    # This efficiently checks for existence and adds the element in one step.
    return char unless seen.add?(char)
  end

  nil
end

# Test cases adapted from your C++ examples
test_cases = [
  "abca",
  "abcbd",
  "abcde",
  "abcdxypcbop",
  "abcdxypcbadom"
]

test_cases.each do |tc|
  result = find_last_repeated_character(tc)
  # Print ' ' if nil, mirroring the C++ ternary expression (result ? result : ' ')
  output = result ? result : ' '
  puts "findLastRepeatedCharacter(#{tc.inspect}) -> #{output}"
end


# run:
#
# findLastRepeatedCharacter("abca") -> a
# findLastRepeatedCharacter("abcbd") -> b
# findLastRepeatedCharacter("abcde") ->  
# findLastRepeatedCharacter("abcdxypcbop") -> p
# findLastRepeatedCharacter("abcdxypcbadom") -> d
# 

 



answered Nov 1 by avibootz
...