给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
示例 1:
输入: J = "aA", S = "aAAbbbb"
输出: 3
示例 2:
输入: J = "z", S = "ZZ"
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jewels-and-stones
class Solution
{
public int numJewelsInStones(String J, String S)
{
if(J.length()==0||S.length()==0)
{
return 0;
}
int counts = 0;
boolean[] alphabet = new boolean[52];
char[] jChars = J.toCharArray();
char[] sChars = S.toCharArray();
for (char ch:jChars)
{
if(ch>=97)
{
alphabet[ch-97] = true; //'A'-65,'a'-97
}
else
{
alphabet[ch-39] = true;
}
}
for (char ch:sChars)
{
if(ch>=97)
{
if(alphabet[ch-97]) counts++;
}
else
{
if(alphabet[ch-39]) counts++; //ch-65+26
}
}
return counts;
}
}