000 name

Description

You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:


Input: J = "z", S = "ZZ"
Output: 0

Note:

S and J will consist of letters and have length at most 50. The characters in J are distinct.

分析和方案

把J当成是宝石材料,判断S中用了几次J的宝石

/**
 * @param {string} J
 * @param {string} S
 * @return {number}
 */
var numJewelsInStones = function(J, S) {

    var M = {}
    var count = 0
    for(i = 0; i < J.length; i++){
        M[J[i]]=true
    }
    for(i = 0; i < S.length; i++){
        if(M[S[i]]){
            count ++
        }
    }
    return count
};

最快

/**
 * @param {string} J
 * @param {string} S
 * @return {number}
 */
var numJewelsInStones = function(j, s) {
  let jArr = j.split('');
  let sArr = s.split('');
  let num = 0;
  for (let j in sArr) {
    if (jArr.includes(sArr[j])) {
      num++
    }
  }
  return num;
};

includes 性能比 indexOf 好一些吗?

参考阅读:Includes() vs indexOf() in JavaScript

第二

var numJewelsInStones = function(J, S) {
    var jewelTypes = J.split('');
    var stones = S.split('');

    var numJewels = 0;
    stones.forEach(function (stone) {
        if (jewelTypes.indexOf(stone) !== -1) {
            numJewels++;
        }
    });
    return numJewels;
};

第三

const numJewelsInStones = function(J, S) {
    const map = {};
    for(let i = 0; i < J.length; i++){
        map[J[i]] = 1;
    }

    let counter = 0;
    for(let i = 0; i < S.length; i++){
        if (map[S[i]]) {
            counter++;
        }
    }
    return counter;    
};

results matching ""

    No results matching ""