Kotlin Leetcode - 771. Jewels and Stones
題目連接: https://leetcode.com/problems/jewels-and-stones/
class Solution {
fun numJewelsInStones(jewels: String, stones: String): Int {
}
}
解題思路
這題相對單純
就是用字串處理和比對
來找出石頭內是否有對應的寶石
Kotlin 參考解答
class Solution {
fun numJewelsInStones(jewels: String, stones: String): Int {
var ans = 0
for (stone in stones) {
if (jewels.contains(stone)) {
ans++
}
}
return ans
}
}
這個邏輯可以更加簡化為一行
class Solution {
fun numJewelsInStones(jewels: String, stones: String) = stones.count { it in jewels }
}
回到 leetcode 列表