package Package1121;
//给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。
//S中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
//J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
import java.util.*;
public class Solution2 {
public int numJewelsInStones(String J, String S){
//创建一个set表储存S的值
Collection<Character> set = new HashSet<>( );
//遍历将其放在哈希表中
for(int i = 0;i < J.length();i++){
set.add(J.charAt( i ));
}
int count = 0;
//遍历S中的每一个元素,判断其是否在J中,如果在count++
for(int i = 0;i < S.length();i++ ){
if (set.contains(S.charAt(i))==true){
count++;
}
}
return count;
}// end numJewelsInStones
public static void main (String[] args){
String a = "aA";
String b = "aAAabbbb";
Solution2 test = new Solution2();
System.out.println(test. numJewelsInStones(a,b) );
}
}//end Solution2
Java实现宝石与石头
最新推荐文章于 2021-12-17 16:58:49 发布