Q771 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".

Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0

Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.

解題思路:

J 用字典或者集合(Python 中判斷集合中元素是否存在也是 O(1) 的時(shí)間)存儲(chǔ)起來,然后遍歷 S 中的每一個(gè)字符,判斷字符是否也出現(xiàn)在 J 中。

時(shí)間復(fù)雜度 O(M+N)

Python 實(shí)現(xiàn):
class Solution:
    # AC: O(len(J) + len(S))
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        J = set(J) # Python 中 set 判斷元素是否存在的時(shí)間復(fù)雜度為 O(1)
        return sum(ch in J for ch in S) 

a = "aA"
b = "aAAbbbb"
print(Solution().numJewelsInStones(a, b))  # 3
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,237評(píng)論 0 23
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,681評(píng)論 5 6
  • 2015年2月到2016年11月,這22個(gè)月我發(fā)生了里里外外的變化,我們管這種變化叫做蛻變。 我來梳理看看, 首先...
    胡芮閱讀 263評(píng)論 0 1
  • 人至中年,對(duì)這一天的到來,十分矛盾也有焦慮。越來越在意它的到來,但也越來越想故意回避。無情的歲月,年輪的痕跡,在肆...
    __天道酬勤__閱讀 478評(píng)論 7 1

友情鏈接更多精彩內(nèi)容