题目链接Jewels and Stones

思路
从题目得知,我们是求字符串J在字符串S中出现的次数。也就是说,one-pass就可以brute force获得答案。
当然可以利用set()数据结构进行优化。

算法复杂度

时间:O(M*N) or O(M + N) where M is the length of J and N is the length of S
空间:O(1) or O(M) where M is the length of J

代码

class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        count = 0
        for s in S:
            if s in J:
                count +=1
        return count
        

用set()优化:

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


xuhang57
17 声望0 粉丝