Try   HackMD

【LeetCode】 771. Jewels and Stones

Description

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".

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

你有一段字串J代表有哪些石頭的種類是珠寶,還有一段字串S代表你有哪些石頭。每一個在S裡面的字元是代表你有的石頭的種類。你想要知道你有的石頭之中有多少珠寶。

這些在J裡面的字母都不相同,並且在JS裡面的字元一定是字母。字母的大小寫是需要在意的,所以aA被視為是不同種類的石頭。

注意:

  • SJ 只包含字母且長度不超過50。
  • J 裡面的字元都不相同。

Example:

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3


Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Solution

  • 用一個hash去紀錄J裡面出現的字。
  • 再用一個迴圈去比對S的字是否出現在hash裡面。

Code

class Solution { public: int numJewelsInStones(string J, string S) { unordered_set<char> hash; int count = 0; for(int i = 0; i < J.length(); i++) hash.insert(J[i]); for(int j = 0; j < S.length(); j++) if(hash.count(S[j])) count++; return count; } };
tags: LeetCode C++