leetcode 771. 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 Sis 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.

 

复制代码
class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        out("", "")=0
        out("", "A")=0
        out("A", "")=0
        out("AB", "C")=0
        out("C", "AB")=0
        out("AB", "AB")=0
        out("ABC", "DEF")=0
        out("ABC", "ABc")=2
        out("ABC", "ABCD")=3
        """
        
        
        '''
        if not J:
            return 0
        jewels = set()
        for j in J:
            jewels.add(j)
        ans = 0
        for s in S:
            if s in jewels:
                ans += 1
        return ans
        '''
    
        setJ = set(J)
        return sum(s in setJ for s in S)
        
复制代码

时间复杂度O(S+J) 空间复杂度 O(S+J)

注: sum([True, False, True])==2

 

posted @   bonelee  阅读(243)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-02-27 linkedin databus介绍——监听数据库变化,有新数据到来时通知其他消费者app,新数据存在内存里,多份快照
2017-02-27 ES忽略TF-IDF评分——使用constant_score
2017-02-27 ES设置字段搜索权重——Query-Time Boosting
2017-02-27 lucene内置的评分函数
2017-02-27 ES搜索排序,文档相关度评分介绍——Vector Space Model
2017-02-27 ES搜索排序,文档相关度评分介绍——TF-IDF—term frequency, inverse document frequency, and field-length norm—are calculated and stored at index time.
2017-02-27 ES搜索排序,文档相关度评分介绍——Field-length norm
点击右上角即可分享
微信分享提示