Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 804. Unique Morse Code Words

題目連接

class Solution {
    fun uniqueMorseRepresentations(words: Array<String>): Int {
        
    }
}

解題思路

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

我們可以利用 map 的概念來處理所有的單字

放到 Kotlin Set 裡面來移除重複的單字

Kotlin 參考解答

class Solution {
    fun uniqueMorseRepresentations(words: Array<String>): Int {
        val morseDictionary = arrayOf(
            ".-",
            "-...",
            "-.-.",
            "-..",
            ".",
            "..-.",
            "--.",
            "....",
            "..",
            ".---",
            "-.-",
            ".-..",
            "--",
            "-.",
            "---",
            ".--.",
            "--.-",
            ".-.",
            "...",
            "-",
            "..-",
            "...-",
            ".--",
            "-..-",
            "-.--",
            "--.."
        )

        return words.map { it.map { c -> morseDictionary[c - 'a'] }.joinToString("") }
                .toSet().size
    }
}

回到 leetcode 列表