天天看點

LeetCode 771: 寶石與石頭 Jewels and Stones

題目:

給定字元串

J

代表石頭中寶石的類型,和字元串

S

代表你擁有的石頭。

S

中每個字元代表了一種你擁有的石頭的類型,你想知道你擁有的石頭中有多少是寶石。

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.

J

中的字母不重複,

J

S

中的所有字元都是字母。字母區分大小寫,是以

"a"

"A"

是不同類型的石頭。

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"

.

示例 1:

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

示例 2:

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

注意:

  • S

    J

    最多含有50個字母。
  • J

    中的字元不重複。

Note:

  • S

    J

    will consist of letters and have length at most 50.
  • The characters in

    J

    are distinct.

解題思路:

J 改為 Set 集合, 周遊 S 即可(因為 Set 查找複雜度為常數)

Java:

class Solution {
    public int numJewelsInStones(String J, String S) {
        Set<Character> set = new HashSet<>();
        for (char c : J.toCharArray())
            set.add(c);
        int count = 0;
        for (char c : S.toCharArray())
            if (set.contains(c)) count++;
        return count;
    }
}           

Python:

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        count = 0
        hash_set = set(J)
        for c in S:
            if c in hash_set:
                count += 1
        return count           

歡迎關注微.信.公..衆号: 愛寫Bug