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

771. Jewels and Stones

作者头像
用户1147447
发布2019-05-26 00:29:55
2440
发布2019-05-26 00:29:55
举报
文章被收录于专栏:机器学习入门

LWC 69: 771. Jewels and Stones

Problem:

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的信息,遍历S,采用Hashmap的思路,每次查询O(1),总时间复杂度为O(n)

Java版本:

代码语言:javascript
复制
    public int numJewelsInStones(String J, String S) {
        int[] count = new int[64];
        for (char c : J.toCharArray()) {
            count[c - 'A']++;
        }
        int ans = 0;
        for (char c : S.toCharArray()) {
            if (count[c - 'A'] >= 1) ans ++;
        }
        return ans;
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        info = set(J)
        ans = 0
        for c in S:
            if c in info: ans += 1
        return ans

再精简一波:

代码语言:javascript
复制
class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        info = set(J)
        return sum(c in info for c in S)     
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年01月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 69: 771. Jewels and Stones
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档