Leetcode学习笔记:#771 Jewels and Stones
You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.
实现:
public int numJewlsInStones(String J, String S){
if(J.length() == 0 || S.length() == 0){
return 0;
}
int[] charToFreq = new int[256];
for(char ch:S.toCharArray()){
charToFreq[ch]++;
}
int numJewels = 0;
for(char ch:J.toCharArray()){
if(charToFreq[ch] > 0){
numJewels += charToFreq[ch];
}
}
return numJewels;
}
思路:
两次遍历。第一次遍历把S的每个char遍历进charToFreq,按ASCII码分配,每有一个相同的char便加1,第二次遍历每发现一个相同的char,便把charToFreq中该char相对应的value加入numJewels中。