LeetCode 771. Jewels and Stones

题目描述 LeetCode 771

You're given strings J representing the types of stones that are jewels, and S
representing the stones you have. Each character in S is a type of stone you have.
You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

题目中文描述

本题大意是,从石头中找珠宝,那么问题来了,什么是石头? 什么又是珠宝呢?
题目告诉我们,现在你有一串字符,如 aAAbbbb(这串字符就是石头),然后呢,珠宝就是事先定义好的 aA(珠宝),在这里,我们可以看到 ‘石头’ 中有 ‘珠宝’ 为 3 个,输出 3 即可

解题思路

石头由字符串 S 给出,珠宝由字符串 J 给出

  • 计算 S 和 J 的各自长度
  • 遍历 S 中的字符,和 J 逐一比较即可(反之亦可)

C语言实现

# include 
# include 

int numJewelsInStones(char *J, char *S)
{
    int sum = 0;
    int j = 0;
    int s = 0;
    int j_length = strlen(J);
    int s_length = strlen(S);

    for (j = 0; j < j_length; j ++ )
    {
        for ( s = 0; s < s_length; s ++)
        {
            if (J[j] == S[s])
            {
                sum++;
            }
        }
    }
    return sum;
}

main()
{
    int sum = 0;
    char j[50];
    char s[50];
    
    scanf("%s",&j);
    scanf("%s",&s);
    sum = numJewelsInStones(j, s);
    printf("sum = %d\n", sum);
}

你可能感兴趣的:(LeetCode 771. Jewels and Stones)