771. 宝石与石头(简单)

1,问题描述

771. 宝石与石头

难度:简单

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

字母区分大小写,因此 "a""A" 是不同类型的石头。

示例 1:

1
2
输入:jewels = "aA", stones = "aAAbbbb"
输出:3

示例 2:

1
2
输入:jewels = "z", stones = "ZZ"
输出:0

提示:

  • 1 <= jewels.length, stones.length <= 50
  • jewelsstones 仅由英文字母组成
  • jewels 中的所有字符都是 唯一的

2,初步思考

​ 直接hashSet+遍历即可

3,代码处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.HashSet;
import java.util.Set;

public class _771宝石与石头 {

// hashSet + 遍历
public int numJewelsInStones(String jewels, String stones) {
Set<Character> set = new HashSet<>();
for (char c : jewels.toCharArray()) {
set.add(c);
}
int sum = 0;
for (char c : stones.toCharArray()) {
if (set.contains(c)) sum++;
}
return sum;
}
}