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,其中J中的每个字符都是珠宝,S中的每个字符都是石头,区分字母的大小写,问我们S中有多少个珠宝。

Java:

public int numJewelsInStones(String J, String S) {
return S.replaceAll("[^" + J + "]", "").length();
}

Java:

public int numJewelsInStones(String J, String S) {
int res = 0;
Set setJ = new HashSet();
for (char j: J.toCharArray()) setJ.add(j);
for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
return res;
} 

Python:

def numJewelsInStones(self, J, S):
return sum(map(J.count, S))

Python:

def numJewelsInStones(self, J, S):
return sum(map(S.count, J))

Python:  

def numJewelsInStones(self, J, S):
return sum(s in J for s in S) 

Python:

def numJewelsInStones(self, J, S):
setJ = set(J)
return sum(s in setJ for s in S)  

Python:

# Time:  O(m + n)
# Space: O(n)
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
lookup = set(J)
return sum(s in lookup for s in S)  

Python: wo

class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
res = 0
for i in S:
if i in J:
res += 1 return res

C++:

int numJewelsInStones(string J, string S) {
int res = 0;
unordered_set<char> setJ(J.begin(), J.end());
for (char s : S) if (setJ.count(s)) res++;
return res;
}

  

  

All LeetCode Questions List 题目汇总

最新文章

  1. 值得推荐的C/C++框架和库
  2. c# 搭建高效分布式web (进一步实现软件的热插拔)
  3. Supermemo背单词7周年纪念
  4. PostgreSQL Errors and Messages
  5. 3563: DZY Loves Chinese - BZOJ
  6. 对stack概念的理解与应用
  7. 为UITextView添加与UITextField一样的边框——UITextField默认边框颜色、宽度、圆角
  8. npm常用命令解析
  9. Redis多实例及主从搭建
  10. nginx+letsencrypt搭建https站点
  11. contos最小包安装完后一些准备
  12. p2394 精度题
  13. Petrozavodsk Winter Camp, Day 8, 2014, Mosaic
  14. 238. Product of Array Except Self除自身以外数组的乘积
  15. golang学习笔记15 golang用strings.Split切割字符串
  16. 经典算法分析:n^2与nlgn
  17. [转载]使用mpvue搭建一个初始小程序
  18. todomvc-app
  19. 拓展javascript内置函数
  20. ie,cookie,域名与下划线

热门文章

  1. 树莓派 Linux 系统命令行快捷键
  2. input 时间字段默认值
  3. 7-html列表
  4. react编写规范之组件组件的内容编写顺序
  5. 利用GitHub+Node.js+Hexo搭建个人博客
  6. vue基本使用及脚手架使用
  7. jsp大附件上传,支持断点续传
  8. mysql 查询账户
  9. 洛谷 P2858 [USACO06FEB]奶牛零食Treats for the Cows 题解
  10. SQL语句操作数据试题