题目
771. 宝石与石头
题解思路
- 题目本身没啥难度,两个for循环就可以解决
- 但是如果使用set可以将时间复杂度优化到o(n)
注:之前python写多了,需要注意c++中string类中是char
代码
C++
class Solution {
public:int numJewelsInStones(string jewels, string stones) {unordered_map<char, int> a;for (auto &c : jewels){a[c] = 1;}int ans = 0;for (auto &c : stones){if (a.count(c)){ans++;}}return ans;}
};
Python
class Solution:def numJewelsInStones(self, jewels: str, stones: str) -> int:dic = set()ans = 0for ch in jewels:dic.add(ch)for ch in stones:if ch in dic:ans += 1return ans