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

1 Answer

0 votes
// 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 ' ' if no character is repeated.
func findLastRepeatedCharacter(_ s: String) -> Character {
    var seen = Set<Character>()
    
    // Iterate through the string's characters in reverse order (right to left)
    for char in s.reversed() {
        // Set.insert returns a tuple where `inserted` is false if the 
        // element was already present in the set.
        if !seen.insert(char).inserted {
            return char
        }
    }
    
    // Return a space character if no duplicates are found (matching C++ style)
    return " "
}

// Test cases adapted from your C++ examples
let testCases = [
    "abca",
    "abcbd",
    "abcde",
    "abcdxypcbop",
    "abcdxypcbadom"
]

for tc in testCases {
    let result = findLastRepeatedCharacter(tc)
    print("findLastRepeatedCharacter(\"\(tc)\") -> \(result)")
}


/*
run:

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

*/

 



answered 5 days ago by avibootz
...