宝石与石头

LeetCode每日一题,771. 宝石与石头

先看题目描述

算法和思路

这题很简单,直接暴力法即可

算法源码

哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

import java.util.HashMap;

class Solution {
public int numJewelsInStones(String J, String S) {
int res = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (char c: J.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 1);
}
}
for (char c: S.toCharArray()) {
if (map.containsKey(c)) res++;
}
return res;
}
}

两层循环遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int numJewelsInStones(String J, String S) {
int res = 0;
for (char s: S.toCharArray()) {
for (char c: J.toCharArray()) {
if (s == c) {
res++;
break;
}
}
}
return res;
}
}