题目:
思路:
- a.暴力法遍历
- b.哈希存储搜索
1 代码(Java)
1.1暴力法
class Solution {
public int numJewelsInStones(String J, String S) {
int jewelsCount = 0;
int jewelsLength = J.length();
int stonesLength = S.length();
for(int i=0;i<stonesLength;i++){
for(int j=0;j<jewelsLength;j++){
if(S.charAt(i)==J.charAt(j)){
jewelsCount++;
break;
}
}
}
return jewelsCount;
}
}
1.2哈希
class Solution {
public int numJewelsInStones(String J, String S) {
int jewelsCount=0;
Set<Character> jewelsSet = new HashSet<Character>();
int jewelsLength = J.length(),stonesLength = S.length();
for(int i=0;i<jewelsLength;i++){
char jewel = J.charAt(i);
jewelsSet.add(jewel);
}
for(int i=0;i<stonesLength;i++){
char stone = S.charAt(i);
if(jewelsSet.contains(stone)){
jewelsCount++;
}
}
return jewelsCount;
}
}
2 代码(python)
2.1暴力法
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return sum(s in J for s in S);
2.2哈希
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
jewelSet = set(J)
return sum(s in jewelSet for s in S);