774. Jewels and Stones

xuhang57發表於2019-02-16

題目連結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)