学号:16340008
Question:
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
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
Answer:
语言用的是C#
思路在于,创造一个数组以记录某个字母是否在J中出现过,为了方便直接创建了长度为128的布尔数组。
因为直接根据字母的ASCII码作为数组索引,因此查阅布尔值可以达到最快速度。
可以做到J和S两个字符串都只遍历一次。
首先遍历J,以获得字母的出现与否,得到比照数组。
然后遍历S,对S中的每个字母,对照上面的数组对应的布尔值,以判断是否对所求数值操作。
public class Solution {
public int NumJewelsInStones(string J, string S) {
int num = 0;
bool[] letters = new bool[128];
char[] Jc = J.ToCharArray();
foreach(char l in Jc) {
letters[l] = true;
}
char[] Sc = S.ToCharArray();
foreach(char l in Sc) {
if (letters[l])
num ++;
}
return num;
}
}