How to check if each letter in a string maps to the first letter of a word in another string with Kotlin

1 Answer

0 votes
fun matchesPattern(pattern: String, sentence: String): Boolean {
    val words = sentence.trim().split(Regex("\\s+"))

    if (pattern.length != words.size) return false

    // Convert 'pattern' to a list/iterable to zip it with the 'words' list
    return pattern.toList().zip(words).all { (p, w) ->
        p.lowercaseChar() == w.first().lowercaseChar()
    }
}


fun main() {
    val pattern = "jpcrg"
    val sentence = "java python c rust go"

    if (matchesPattern(pattern, sentence)) {
        println("Pattern matches!")
    } else {
        println("Pattern does NOT match.")
    }
}




/*
run:

Pattern matches!

*/


 



answered Jan 6 by avibootz

Related questions

...