jzhangnu / Leetcode-JS-Solutions

:tropical_drink: Leetcode solutions using JavaScript.
52 stars 7 forks source link

771. Jewels and Stones #122

Open jzhangnu opened 6 years ago

jzhangnu commented 6 years ago
//ES6
var numJewelsIsStones = function(J,S){
  let hash = new Map();
  let res = 0;

  for(s of S){
    if(!hash.has(s)){
      hash.set(s, 1)
    }else{
      hash.set(s, hash.get(s)+1)
    }
  }

  for(j of J){
    if(hash.has(j)){
      res+=hash.get(j)
    }
  }

  return res
}

var numJewelsIsStones = function(J,S){
  var hash = {};
  var res = 0;

  for(var i=0; i<S.length; i++){
    var v = S.charAt(i);
    if(!hash[v]){
      hash[v] = 1
    }else{
      hash[v]++
    }
  }

  for(var i=0; i<J.length; i++){
    var j = J.charAt(i);

    if(hash[j]){
      res += hash[j]
    }  
  }

  console.log(res)
  return res
}
ruhignieh commented 5 years ago

var numJewelsInStones = function(J, S) { return S.split('').filter(char => J.indexOf(char) !== -1).length; };