暴力解法
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: total = 0 for j in J: for s in S: if s == j: total+=1 return total
很简单,就不多说了,依次遍历,复杂度O(N²)
hash表
class Solution: def numJewelsInStones(self, J: str, S: str) -> int: mp = {x: 0 for x in J} for s in S: if mp.get(s) is not None: mp[s] += 1 return sum(mp.values())
- 先创建一个map, 里面存放类型
- 遍历字符串,如果找到了类型,则map里面的值+1
- 累加所有map的value