LeetCode771-宝石与石头

题目链接

英文链接:https://leetcode.com/problems/jewels-and-stones/

中文链接:https://leetcode-cn.com/problems/jewels-and-stones/

题目详述

给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

J 中的字母不重复,JS中的所有字符都是字母。字母区分大小写,因此"a""A"是不同类型的石头。

示例 1:

1
2
输入: J = "aA", S = "aAAbbbb"
输出: 3

示例 2:

1
2
输入: J = "z", S = "ZZ"
输出: 0

注意:

  • SJ 最多含有50个字母。
  • J 中的字符不重复。

题目详解

  • 运用哈希表存储所有的宝石。
  • 遍历所有石头,在哈希表中查找进行判断是否为宝石。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class LeetCode_00771 {

public int numJewelsInStones(String J, String S) {
Set<Character> set = new HashSet<>();
for (char c : J.toCharArray()) {
set.add(c);
}
int res = 0;
for (char c : S.toCharArray()) {
if (set.contains(c)) {
++res;
}
}
return res;
}
}
  • 还可以运用正则表达式,在石头串中去掉所有不是宝石的石头。
  • 得到的石头串所有石头全部为宝石,它的长度即为所求。
1
2
3
4
5
6
public class LeetCode_00771 {

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