LeetCode 771 宝石与石头 HERODING的LeetCode之路

给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。

示例 1:

输入: J = “aA”, S = “aAAbbbb”
输出: 3

示例 2:

输入: J = “z”, S = “ZZ”
输出: 0

注意:

S 和 J 最多含有50个字母。
J 中的字符不重复。

解题思路:
终于盼来了一道简单题,这道题目也有多种解题思路,一个是暴力破解的方法,直接遍历,时间复杂度为O(mn),另一种是使用Set,Set可以储存宝石的字母,然后用count函数进行比对,很快就能的出结果,代码如下:

class Solution {
    
    
public:
    int numJewelsInStones(string J, string S) {
    
    
        int count = 0;
        int len1 = J.length();
        int len2 = S.length();
        for(int i = 0; i < len2; i ++){
    
    
            char stone = S[i];
            for(int j = 0; j < len1; j ++){
    
    
                char jew = J[j];
                if(stone == jew){
    
    
                    count ++;
                }
            }
        }
        return count;
    }
};

使用Set的方法

class Solution {
    
    
public:
    int numJewelsInStones(string J, string S) {
    
    
        int count = 0;
        unordered_set<char> jewSet;
        int len1 = J.length();
        int len2 = S.length();
        for(int i = 0 ; i < len1; i ++){
    
    
            char jewel = J[i];
            jewSet.insert(jewel);
        }
        for(int i = 0; i < len2; i ++){
    
    
            char stone = S[i];
            if(jewSet.count(stone)){
    
    
                count ++;
            }
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/108899445