C#LeetCode刷题之#771-宝石与石头(Jewels and Stones)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3812 访问。

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

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

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

输出: 3

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

输出: 0

注意:

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


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".

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

Output: 3

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.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3812 访问。

public class Program {

    public static void Main(string[] args) {
        var J = "aA";
        var S = "aAAbbbb";

        var res = NumJewelsInStones(J, S);
        Console.WriteLine(res);

        J = "z";
        S = "ZZ";

        res = NumJewelsInStones2(J, S);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int NumJewelsInStones(string J, string S) {
        var res = 0;
        foreach(var c in S) {
            if(J.Contains(c)) res++;
        }
        return res;
    }

    private static int NumJewelsInStones2(string J, string S) {
        var res = 0;
        var set = new HashSet();
        foreach(var c in J) {
            set.Add(c);
        }
        foreach(var c in S) {
            if(set.Contains(c)) res++;
        }
        return res;
    }

}

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3812 访问。

3
0

分析:

设石头的类型数量为 m,拥有的石头的数量为 n ,那么NumJewelsInStones 的时间复杂应当为: O(m*n) ,NumJewelsInStones2的时间复杂为: O(n) 。

你可能感兴趣的:(C#LeetCode刷题,C#LeetCode)