771. Jewels and Stones
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"
.
(1) -> 常常出现在函数名后面,描述函数的返回类型,如:
def add(x,y)->int: #函数的返回类型为int
return x+y
(2)@property是一个装饰器,能够使得类把一个方法变成属性调用。如:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('score must be an integer!')
if score<0 or score>100:
raise ValueError('score must between 0~180')
self._score = value
s = Student()
s.score = 60
s.score = 9999 #ValueError
(3)解题:
class Solution: def numJewelsInStones(self, J:'str', S:'str') -> 'int': num = 0 for s in S: if s in J: num += 1 return num s = Solution() n = s.numJewelsInStones("z","ZZ") print(n)
优化:
class Solution: def numJewelsInStones(self, J:'str', S:'str') -> 'int': return sum(s in J for s in S) s = Solution() n = s.numJewelsInStones("z","ZZ") print(n)
#方法二:使用str的count属性 def numJewelsInStones(self, J:'str', S:'str') -> 'int': return sum(map(S.count,J))