[leetcode] roman to int in kotlin

최대한·2023년 9월 15일

https://leetcode.com/problems/roman-to-integer/description/

fun romanToInt(s: String): Int {
    val symbols = mapOf(
        'I' to 1,
        'V' to 5,
        'X' to 10,
        'L' to 50,
        'C' to 100,
        'D' to 500,
        'M' to 1000,
    )
    val mixed = mapOf(
        "IV" to 4,
        "IX" to 9,
        "XL" to 40,
        "XC" to 90,
        "CD" to 400,
        "CM" to 900,
    )

    var res = 0
    val checked = mutableMapOf<Int, Boolean>()
    mixed.forEach { (t, u) ->
        val idx = s.indexOf(t)
        if (idx != -1) {
            res += u
            checked[idx] = true
            checked[idx + 1] = true
        }
    }
    s.mapIndexed { idx, c ->
        if (checked[idx] != null) {
            return@mapIndexed
        }
        res += symbols[c]!!
    }
    return res
}
profile
Awesome Dev!

0개의 댓글