LeetCode 771. 宝石与石头(C、C++、python)

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

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

示例 1:

输入: J = "aA", S = "aAAbbbb"
输出: 3

示例 2:

输入: J = "z", S = "ZZ"
输出: 0

注意:

S 和 J 最多含有50个字母。

J 中的字符不重复。

C

int numJewelsInStones(char* J, char* S) 
{
    int a[52]={0};
    int m=strlen(J);
    int n=strlen(S);
    int count=0;
    for(int i=0;i='a' && J[i]<='z')
        {
            a[J[i]-'a']++;
        }
        else
        {
            a[J[i]-'A'+26]++;
        }
    }
    for(int i=0;i='a' && S[i]<='z')
        {
            if(a[S[i]-'a']>0)
            {
                count++;
            }
        }
        else
        {
            if(a[S[i]-'A'+26]>0)
            {
                count++;
            }
        }
    }
    return count;
}

C++

class Solution {
public:
    int numJewelsInStones(string J, string S) 
    {
        int count=0;
        set tmp;
        int m=J.length();
        int n=S.length();
        for(int i=0;i0)
            {
                count++;
            }
        }
        return count;
    }
};

python

class Solution:
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        n=len(S)
        tmp=list(J)
        count=0
        for i in range(n):
            if tmp.count(S[i])>0:
                count+=1
        return count

 

你可能感兴趣的:(LeetCode)