题目描述:
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:
• S and J will consist of letters and have length at most 50.
• The characters in J are distinct.
class Solution {
public:
int numJewelsInStones(string J, string S) {
unordered_map<char,bool> hash;
for(char c:J) hash[c]=true;
int result=0;
for(char c:S) if(hash.count(c)) result++;
return result;
}
};
本文解析了一种算法,用于计算给定字符串中特定字符(宝石)的数量。通过使用哈希映射,算法能高效地从一堆石头(字符串)中找出宝石(目标字符)。文章详细介绍了算法的实现过程及示例。
461

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



