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

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

问题

给定字符串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.

示例

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<char>();
        foreach(var c in J) {
            set.Add(c);
        }
        foreach(var c in S) {
            if(set.Contains(c)) res++;
        }
        return res;
    }

}

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

3
0

分析:

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

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3812

发表评论

登录后才能评论