一、Java
- class Solution {
- public int numJewelsInStones(String jewels, String stones) {
- int[] isJewel = new int['z' + 1];
- for (int i = jewels.length() - 1; i >= 0; i--) isJewel[jewels.charAt(i)] = 1;
- int cnt = 0;
- for (int i = stones.length() - 1; i >= 0; i--) cnt += isJewel[stones.charAt(i)];
- return cnt;
- }
- }
二、C++
- #include
-
- using namespace std;
-
- class Solution {
- public:
- int numJewelsInStones(string jewels, string stones) {
- int isJewel['z' + 1] = {};
- for (char c: jewels) isJewel[c] = 1;
- int cnt = 0;
- for(char c: stones) cnt += isJewel[c];
- return cnt;
- }
- };
三、Python
- class Solution:
- def numJewelsInStones(self, jewels: str, stones: str) -> int:
- isJewel = set(jewels)
- cnt = 0
- for c in stones:
- if c in isJewel:
- cnt += 1
- return cnt
四、JavaScript
- var numJewelsInStones = function(jewels, stones) {
- let isJewel = new Set(jewels);
- let cnt = 0;
- for(let c of stones) {
- if(isJewel.has(c)) cnt++;
- }
- return cnt;
- };
五、Go
- package main
- func numJewelsInStones(jewels string, stones string) int {
- var isJewel ['z' + 1]int
- for _, c := range jewels {
- isJewel[c] = 1
- }
- cnt := 0
- for _, c := range stones {
- cnt += isJewel[c]
- }
- return cnt
- }