Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 2325. Decode the Message

題目連接

class Solution {
    fun decodeMessage(key: String, message: String): String {
    }
}

解題思路

這一題考的是對字串的處理

會需要用到 HashMap

Kotlin 參考解答

class Solution {
    fun decodeMessage(key: String, message: String): String {
        val code = HashMap<Char, Char>()
        code[' '] = ' '
		
        var localKey = key.toSet()
            .joinToString("")
            .filter { it != ' ' }
        localKey.forEachIndexed { i, _ ->
            code[localKey[i]] = ('a'..'z').toList()[i]
        }
        
        var result = StringBuilder()
        message.forEachIndexed { i, _ ->
            result.append(code[message[i]])
        }
        
        return result.toString()
    }
}

回到 leetcode 列表