1. 程式人生 > >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) 。