1. Jewels and Stones

Title:

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

Example 1:

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

Example 2:

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.

Analysis of Title:

1.Give us the J and the S

2.J in S

3.Need to select J from S and letters are case sensitive.

4.Non-repetitive statistics how many J are in S

so,

1.go through all J

2.achieve case sensitive

3.achieve Non-repetitive

Test case:

  "aA"
  "aAAbbbb"

Python:

class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        return sum(1 for s in S if s in set(J))

Analysis of Code:

1.It meas go through S and get s in S if s in J Non-repetitive, and if get successful, add a 1 in tuple, then sum the tuple.

2.set(J) return de-duplication J

3.sum()  sum(iterable)  sum all the value in iterable object

  example:sum((1,2,3))

  >6

4.(1 for s in S if s in set(J))

  This is a generator, it means to create a tuple that len be equal to how many "for s in S if s in set(J)" successful, and now it's (1,1,1)

原文地址:https://www.cnblogs.com/sxuer/p/10628600.html