每日一题(注意string里是char)-771. 宝石与石头

题目

771. 宝石与石头

题解思路

  • 题目本身没啥难度,两个for循环就可以解决
  • 但是如果使用set可以将时间复杂度优化到o(n)

注:之前python写多了,需要注意c++中string类中是char

代码

C++

class Solution {
public:
    int numJewelsInStones(string jewels, string stones) {
        unordered_map 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

你可能感兴趣的:(Leetcode每日一题,leetcode,python,c++)