Leetcode: 771
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”.
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Note:
- S and J will consist of letters and have length at most 50.
- The characters in J are distinct.
Solution:
class Solution {
public int numJewelsInStones(String J, String S) {
//--------my slow solution
// String[] as = S.split("");
// String[] js = J.split("");
// int count = 0;
// for(String e : as){
// int len = js.length - 1;
// while(len >= 0){
// if( js[len].equals(e) ){
// count++;
// len = 0;
// }
// len --;
// }
// }
// return count;
// //optimization
// int count = 0;
// String[] as = S.split("");
// for(String e : as){
// if( J.indexOf(e) >= 0) count++;
// }
// return count;
//3rd most fast than others
// HashSet<Character> hs = new HashSet<>();
// for(char c:J.toCharArray())
// hs.add(c);
// int cnt = 0;
// for(char c:S.toCharArray()){
// if(hs.contains(c))
// cnt++;
// }
// return cnt;
//4th
return S.replaceAll("[^" + J + "]", "").length();
}
}