Jewels and Stones

题目如下

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in Sis 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".

一言以蔽之,希望从S中找出包含的J中的字符的种类数。

直接的方式方法应该是hash映射法。

算法思想

0. 设定参数cnt用于记录S中存在的宝石数目

1. 将J中的字符映射为hash数组(字母有ascii的话需设定hash数组长度256)(J中存在的字符,hash数组中对应的ascii码编号位置处设为1)

2.读取S中的字符c,如果hash[c] = 1,则cnt++;

3.返回cnt

代码实现

1. java代码

 1 class Solution {
 2     public int numJewelsInStones(String J, String S) {
 3         int[] hash = new int[256];
 4         int ans = 0;
 5         for(int i=0; i<J.length(); i++)
 6         {
 7             hash[J.charAt(i)] = 1;
 8         }
 9         for(int i=0; i<S.length(); i++)
10         {
11             if(hash[S.charAt(i)] == 1) ans++;
12         }
13         return ans;
14     }
15 }
原文地址:https://www.cnblogs.com/Sinkinghost/p/8504479.html