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

3 Answers

0 votes
fun getFirstRepeatedCharacter(s: String): Char {
    val len = s.length

    for (i in 0 until len) {
        for (j in 0 until i) {
            if (s[i] == s[j]) {
                return s[i]
            }
        }
    }

    return ' '
}

fun main() {
    val s = "abcdxypcbop"
    val result = getFirstRepeatedCharacter(s)

    if (result != '-') {
        println("First repeated character: $result")
    } else {
        println("No repeated characters")
    }
}
 
 
 
  
/*
run:
    
First repeated character: c
    
*/

 



answered Dec 2, 2024 by avibootz
0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 * "abca"         -> 'a'
 * "abcbd"        -> 'b'
 * "abcde"        -> null
 * "abcdxypcbop"  -> 'c'
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param input The input string.
 * @return The first repeated character, or null if none exists.
 */
fun findFirstRepeatedCharacter(input: String): Char? {
    val seen: MutableSet<Char> = mutableSetOf()

    for (ch in input) {
        // add() returns false if the character
        // is already present in the set.
        if (!seen.add(ch)) {
            return ch
        }
    }

    // No repeated character found.
    return null
}

fun main() {
    println(findFirstRepeatedCharacter("abca"))         // a
    println(findFirstRepeatedCharacter("abcbd"))        // b
    println(findFirstRepeatedCharacter("abcde"))        // null
    println(findFirstRepeatedCharacter("abcdxypcbop"))  // c
}


/*
run:

a
b
null
c

*/

 



answered 6 days ago by avibootz
0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 * "abca"         -> 'a'
 * "abcbd"        -> 'b'
 * "abcde"        -> null
 * "abcdxypcbop"  -> 'c'
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param input The input string.
 * @return The first repeated character, or null if none exists.
 */
fun findFirstRepeatedCharacter(input: String): Char? {
    val seen: MutableSet<Char> = mutableSetOf()

    for (ch in input) {
        // add() returns false if the character
        // is already present in the set.
        if (!seen.add(ch)) {
            return ch
        }
    }

    // No repeated character found.
    return null
}

fun main() {
    val testCases = listOf(
        "abca",
        "abcbd",
        "abcde",
        "abcdxypcbop"
    )

    for (input in testCases) {
        val result = findFirstRepeatedCharacter(input)

        println(result ?: "No repeated character")
    }
}


/*
run:

a
b
No repeated character
c

*/

 



answered 6 days ago by avibootz
...