class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ cnt = 0 for char in S: if char in J: cnt += 1 return cnt
41 ms
-------------------------------------------------------------
class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ return sum(s in J for s in S)
42ms反而耗时增加,自己手动设置一个变量计数比调用sum()函数更省时间
----------------------------------------------------------------
class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ return sum(map(S.count, J))
59ms耗时增加更多,想一下,每个J中的元素(这里J是一个迭代器,迭代器中每个元素都实施map中的第一个参数的函数调用)都要遍历一遍S做count,复杂度相当于S×J
--------------------------------------------------------------------
class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ cnt = 0 for char in J: cnt += S.count(char) return cnt
41ms,回到第一种解法
好想知道最优时间解,查遍了没找着。。41ms只是打败71%的solver