771. Jewels and Stones

771. Jewels and Stones

Question

You’re given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.

Letters are case sensitive, so "a" is considered a different type of stone from "A".

Solution

数组统计,先遍历宝石,记录宝石的位置。
然后遍历石头,如果对应的位置已被记录则计数加一。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int numJewelsInStones(String jewels, String stones) {
int ret = 0;
int[] bin = new int[58];
for(char c : jewels.toCharArray()){
bin[c-'A']++;
}

for(char c : stones.toCharArray()){
if(bin[c-'A'] != 0) ret++;
}
return ret;
}
}
Author

Xander

Posted on

2022-06-21

Updated on

2022-06-21

Licensed under

Comments