学号: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 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".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
SandJwill consist of letters and have length at most 50.- The characters in
Jare 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;
}
}

本文介绍了一种使用C#实现的高效算法,用于计算给定字符串中属于特定类型(珠宝)字符的数量。该算法通过建立一个布尔数组来标记哪些字符是有效的珠宝字符,并通过对输入字符串进行一次遍历即可得出结果。
706

被折叠的 条评论
为什么被折叠?



