給兩個字串 J、S ,J裡面的字符是代表jewel,問 S 裡面有幾個 jewel。
這是一個相當簡單的問題,重點會放在用什麼作為搜尋的方式。
為了快速,這裡會使用 hash 家族的資料型態讓搜尋更快速。
如果是Python會用 set 或 dict 都可以,我用 collections.Counter, 只是換一點寫法。collection.Counter 是 dict 類的。
如果是C#,我直接用 string 的 Contains() ,其實做法都大同小異。
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
counter = Counter(S)
return sum([counter[j] for j in set(J)])
C#
public class Solution {
public int NumJewelsInStones(string J, string S) {
int result = 0;
foreach(var s in S)
{
if(J.Contains(s))
result += 1;
}
return result;
}
}