【LeetCode】每日一题 771. 宝石与石头

51 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情

771. 宝石与石头

给你一个字符串 jewels 代表石头中宝石的类型,另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。

字母区分大小写,因此 "a" 和 "A" 是不同类型的石头。

「示例1:」
输入:jewels = "aA", stones = "aAAbbbb"
输出:3
「示例2:」
输入:jewels = "z", stones = "ZZ"
输出:0
「提示:」
1 <= jewels.length, stones.length <= 50
jewels 和 stones 仅由英文字母组成
jewels 中的所有字符都是 唯一的

解题思路

1. 遍历多的,对少的执行 Array.includes()
  return S_arr.filter(item => J.includes(item)).length;
2. 使用遍历多的,对少的执行 String.indexOf()
  return S_arr.filter(item => J.indexOf(item) > -1).length;
3.  const J_arr = J.split('');
    let count = 0;
    for(let i = 0, len = J.length; i < len; i++){
         count+= findAllEqChart(J_arr[i], S);
    }
    return count;
4.  return J.split('').reduce((count, item) => count + findAllEqChart(item, S) ,0);

代码实现

​
var numJewelsInStones = function(J, S) {
​
    // const S_arr = S.split(''), J_arr=J.split('');
    // 法1: 遍历多的,对少的执行 Array.includes() ,68~96ms
    // return S_arr.filter(item => J.includes(item)).length;
​
    // 法2: 使用遍历多的,对少的执行 String.indexOf() 稳定在 76ms
    // return S_arr.filter(item => J.indexOf(item) > -1).length;
​
    // 法3: 稳定在 80ms
    // const J_arr = J.split('');
    // let count = 0;
    // for(let i = 0, len = J.length; i < len; i++){
    //     count+= findAllEqChart(J_arr[i], S);
    // }
    // return count;
    // 法4, 68ms (80%), 内存 34.8(20%)
    return J.split('').reduce((count, item) => count + findAllEqChart(item, S) ,0);
};
​
/**
 * 查找多个重复的总计数量
 * 优点,遍历少的节点,对多的节点使用 String.indexOf() 查找
 */
const findAllEqChart = (chart, str) => {
    let count = 0, i = 0, len = str.length;
    do {
        let found = str.indexOf(chart, i);
        if( found > -1){
            count++;
            i = found + 1;
        } else {
            i = len
        }
    } while (i < len)
    return count;
}

如果你对这道题目还有疑问的话,可以在评论区进行留言;