问题描述:
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”.
jewels的字符代表宝石,stones里面的字符代表石头,判断石头里有多少块宝石
思路:
用哈希表统计每块石头出现的数量,如果他是宝石,就累加到计数器里面
代码如下:
class Solution {
public int numJewelsInStones(String jewels, String stones) {
Map<Character, Integer> map=new HashMap<>();
int counter=0;
for(int i=0; i<stones.length(); i++){
if(!map.containsKey(stones.charAt(i))){
map.put(stones.charAt(i), 1);
}
else{
map.put(stones.charAt(i), map.get(stones.charAt(i))+1);
}
}
for(int i=0; i<jewels.length(); i++){
if(map.containsKey(jewels.charAt(i))) counter=counter+map.get(jewels.charAt(i));
}
return counter;
}
}
时间复杂度:O(n)