LeetCode771 宝石与石头
题目
解题
// javascript
var numJewelsInStones = function(jewels, stones) {
const jewelSet = new Set(Array.from(jewels));
let cnt = 0;
for (const stone of stones) {
if (jewelSet.has(stone) === true) {
cnt++;
}
}
return cnt;
};
高级写法:使用 reduce 函数
// javascript
var numJewelsInStones = function(jewels, stones) {
const jewelsSet = new Set(jewels.split(''));
return stones.split('').reduce((prev, val) => {
return prev + jewelsSet.has(val);
}, 0);
};