[LeetCode刷題筆記] 771 - Jewels and Stones
題目描述:
You’re given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: jewels = "aA", stones = "aAAbbbb"
Output: 3
Example 2:
Input: jewels = "z", stones = "ZZ"
Output: 0
Constraints:
1 <= jewels.length, stones.length <= 50jewelsandstonesconsist of only English letters.- All the characters of
jewelsare unique.
一刷題解(HashSet):
這題給了我們兩個數組,一個是「石頭」數組,一個是「寶石」數組。「石頭」數組給了我們一系列的大/小寫的英文字母,這些英文字母代表著一些石頭;「寶石」數組則給了一些不重複的大/小寫英文字母,在「寶石」數組出現了的字母有可能會與「石頭」數組中出現的字母重複,重複了的字母代表著「這些石頭是寶石」。
因此我們只要把寶石數組的元素加到一個HashSet中,再遍歷石頭數組,如果寶石HashSet中包含了石頭數組的元素,寶石計數遞增。
public class Solution {
public int NumJewelsInStones(string jewels, string stones) {
if(jewels.Length == 0 || stones.Length == 0) { return 0; }
HashSet<char> jewelHash = jewels.ToHashSet<char>();
int jewelCnt = 0;
foreach (char s in stones)
{
if (jewelHash.Contains(s))
{
jewelCnt++;
}
}
return jewelCnt;
}
}