題目
771. 寶石與石頭文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-606189.html
題解思路
- 題目本身沒(méi)啥難度,兩個(gè)for循環(huán)就可以解決
- 但是如果使用set可以將時(shí)間復(fù)雜度優(yōu)化到o(n)
注:之前python寫(xiě)多了,需要注意c++中string類中是char文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-606189.html
代碼
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 = 0
for ch in jewels:
dic.add(ch)
for ch in stones:
if ch in dic:
ans += 1
return ans
到了這里,關(guān)于每日一題(注意string里是char)-771. 寶石與石頭的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!