LeetCode771 宝石与石头
作者:互联网
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);
};
标签:stones,cnt,return,宝石,reduce,jewels,石头,LeetCode771,const 来源: https://blog.csdn.net/weixin_45561634/article/details/121161577