Article Directory
topic
771. Gems and Stones
The given string J represents the type of gem in the stone, and the string S represents the stone you own. Each character in S represents a type of stone you own, and you want to know how many of the stones you own are gems.
The letters in J are not repeated, and all the characters in J and S are letters. Letters are case-sensitive, so "a" and "A" are different types of stones.
Example 1:
输入: J = "aA", S = "aAAbbbb"
输出: 3
Example 2:
输入: J = "z", S = "ZZ"
输出: 0
note:
S 和 J 最多含有50个字母。
J 中的字符不重复。
Problem solution (Java)
class Solution
{
public int numJewelsInStones(String jewels, String stones)
{
//获取所有的宝石,保存在数组中
char[] c = new char[jewels.length()];
//获取jewels中所有的宝石
for(int index = 0;index < jewels.length();index++)
{
c[index] = jewels.charAt(index);
}
//判断stones中宝石的个数
int count = 0;
for(int index = 0;index < stones.length();index++)
{
//如果有宝石
if(contained(stones.charAt(index),c))
{
count++;
}
}
return count;
}
//判断temp中是否有宝石
public boolean contained(char c, char[] temp)
{
for(int index = 0;index < temp.length;index++)
{
if(temp[index] == c)
{
return true;
}
}
return false;
}
}