LeetCode 771: gems and stones Jewels and Stones

topic:

Given the string Jrepresents the type of gem stones, strings and Srepresentatives of stones you have. SEach character represents a type of stone you have, you want to know the stone you have in how many gems.

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.

JThe letters are not repeated, Jand Sall characters are letters. Case sensitive, therefore "a", and "A"different types of stones.

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:

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

Example 2:

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

note:

  • SAnd Jcontain up to 50 letters.
  • J The characters are not repeated.

Note:

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

Problem-solving ideas:

Set J to set, to traverse the S (Set lookup because complexity is constant)

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

Welcome attention to micro-channel public public .. No: Love Bug write

I love to write Bug.jpeg

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/12022556.html