前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q771 Jewels and Stones

Q771 Jewels and Stones

作者头像
echobingo
发布2018-04-25 17:18:57
7280
发布2018-04-25 17:18:57
举报
文章被收录于专栏:Bingo的深度学习杂货店

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:
代码语言:javascript
复制
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
代码语言:javascript
复制
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) 的时间)存储起来,然后遍历 S 中的每一个字符,判断字符是否也出现在 J 中。

时间复杂度 O(M+N)

Python 实现:
代码语言:javascript
复制
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 判断元素是否存在的时间复杂度为 O(1)
        return sum(ch in J for ch in S) 

a = "aA"
b = "aAAbbbb"
print(Solution().numJewelsInStones(a, b))  # 3
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.03.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • 解题思路:
  • Python 实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档