LeetCode 题目地址
描述
You're given stringsJrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters inJare guaranteed distinct, and all characters inJandSare 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
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
SandJwill consist of letters and have length at most 50.- The characters in
Jare distinct.
题目意思是,字符串J代表石头中宝石的类型,字符串S中每个字符代表了一种石头类型,求S中有多少石头是宝石。
J中的字母不重复,J和S中的所有字符都是字母。字母区分大小写,因此"a"和"a"是不同类型的石头。
解法一:循环判断
这种方法很简单,循环字符串 S,判断字符串S中的每个字符是否存在 字符串J中。
public int numJewelsInStones(String J,String S){
// 入参判断
if(J == null || J.isEmpty()){
return 0;
}
if(S == null || S.isEmpty()){
return 0;
}
if(J.length() > 50 || S.length() > 50){
throw new IllegalArgumentException("请输入合法字符串");
}
if(!J.matches("[a-zA-Z]+") || !S.matches("[a-zA-Z]+")){
throw new IllegalArgumentException("请输入合法字符串");
}
int count = 0;
char[] charsS = S.toCharArray();
for(char c:charsS){
if(J.indexOf(c) > -1){
count ++;
}
}
return count;
}解法二:正则表达式
discuss 中看到的一种解法,超级简单。用正则表达式匹配,删除S字符串中非J中字符的部分,返回其长度。
public int numJewelsInStones(String J,String S){
return S.replaceAll("[^" + J + "]","").length();
}GitHub 代码地址