Find Last Repeated Character in a string
Code
func findLastRepeatedCharacter(_ input: String) -> Character? {
var charDict: [Character: Int] = [:]
// Count the occurrence of each character
for char in input {
if let count = charDict[char] {
charDict[char] = count + 1
} else {
charDict[char] = 1
}
}
// Iterate through the characters in reverse order
for char in input.reversed() {
if let count = charDict[char], count > 1 {
return char
}
}
return nil
}
Example
// Example usage
let inputString = "Hello, playground"
if let lastRepeatedChar = findLastRepeatedCharacter(inputString) {
print("The last repeated character is: \(lastRepeatedChar)")
} else {
print("No repeated characters found.")
}
Output
The last repeated character is: o