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

1 Answer

0 votes
// Finds the last repeated character in a string.
// Scans the string from right to left using a MutableSet to track seen characters.
// Returns the character, or ' ' if no character is repeated.
fun findLastRepeatedCharacter(s: String): Char {
    val seen = mutableSetOf<Char>()

    // Iterate through the string's characters from right to left
    for (c in s.reversed()) {
        // MutableSet.add() returns false if the element was already present in the set.
        // This checks existence and adds the element in a single efficient operation.
        if (!seen.add(c)) {
            return c
        }
    }

    // Return a space character if no duplicates are found (matching C++ style)
    return ' '
}

fun main() {
    // Test cases adapted from your C++ examples
    val testCases = listOf(
        "abca",
        "abcbd",
        "abcde",
        "abcdxypcbop",
        "abcdxypcbadom"
    )

    for (tc in testCases) {
        val result = findLastRepeatedCharacter(tc)
        println("findLastRepeatedCharacter(\"$tc\") -> $result")
    }
}


/*
run:

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

*/

 



answered 5 days ago by avibootz
...