Link: https://leetcode.com/problems/jewels-and-stones/submissions/
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 and J will consist of letters and have length at most 50.
- The characters in J are distinct.
題目翻譯:
你得到的字符串 J 代表珠寶的石頭類型,S 代表你擁有的寶石。 S 中的每個角色都是你擁有的一種石頭。你想知道你有多少寶石也是珠寶。
J 中的字母保證不同,J 和 S 中的所有字符都是字母。字母區分大小寫,因此“a”被認為是與“A”不同類型的石頭。
程式思路:
建立一個珠寶石頭類型 hash table 在比對自已擁有的珠寶,就能輕鬆解題。
class Solution {
public:
int numJewelsInStones(string J, string S) {
unsigned int ret = 0;
std::unordered_map<char,int> umap;
for (unsigned i=0; i<J.length(); ++i)
{
umap.insert( pair<char, int>( J.at(i), i));
}
for (unsigned i=0; i<S.length(); ++i)
{
if(umap.find(S.at(i)) != umap.end())
ret ++;
}
return ret;
}
};