774. Jewels and Stones

题目链接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
    原文地址: https://segmentfault.com/a/1190000015577331
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞