欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

letCode(771 Jewels and Stones )

程序员文章站 2022-06-28 10:51:24
问题描述: 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 o ......

问题描述:

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

解决方案:

  1 数组

    var numjewelsinstones = function(j, s) {
    var arr1=j.split("");
    var arr2=s.split("");
    var count=0;
    for(var i=0;i<arr2.length;i++){
    for(var j=0;j<arr1.length;j++){
    if(arr2[i]==arr1[j]){
    count++
    }
    }
    }
    return count
    };

      2 字符串方法

    

    var numjewelsinstones = function(j, s) {
    var count=0;
    for(var i=0;i<s.length;i++){
    if(j.indexof(s.charat(i))!==-1){
    count++
    }
    }
    return count
    };