69 - 771. Jewels And Stones

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.

Code in C++:

int numJewelsInStones(string J, string S) {
    if(J.empty()) return 0;
    
    int counter=0;
    unordered_map<char, int> m;
    for(char& stone: S)   //count the occurrences of each character
        m[stone]++;
    
    for(char& jewel: J) {
        if(m.find(jewel)!=m.end())   //increment counter for each character in `jewel`
            counter+=m[jewel];
    }
    
    return counter;
}

注解:
1)用unordered_map统计S中字符出现的次数。。
2)将J依次与unordered_map对比,若是jewel,则加上该字符出现的次数。

Discuss地址:
https://discuss.leetcode.com/category/1726/jewels-and-stones

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容