#LeetCode:771. Jewels and Stones

灆洢 2020-05-03 11:56:03

此題想找出的是 J 字串中的各個字元在 S 字串中出現的次數總和。

將 J 字串的各個字集結起來形成一個 Set,並巡覽 S 字串中的各個字元看有沒有在 J 字串形成的 Set 中出現即可。

Kotlin(280ms)

/*******************************************************
 * LeetCode 771. Jewels and Stones                     *
 * Author: Maplewing [at] knightzone.studio            *
 * Version: 2020/05/03                                 *
 *******************************************************/
class Solution {
    fun numJewelsInStones(J: String, S: String): Int {
        val isJewelSet = J.toSet()
        return S.count { isJewelSet.contains(it) }
    }
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料