Leetcode 771. Jewels and Stones

Lintcode 1038. 珠宝和石头

Posted by Olivia Liu on May 2, 2020 | 阅读:

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

给定字符串J代表是珠宝的石头类型,而S代表你拥有的石头.S中的每个字符都是你拥有的一个石头. 你想知道你的石头有多少是珠宝。

J中的字母一定不同,JS中的字符都是字母。 字母区分大小写,因此"a""A"是不同的类型。

Examples

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

Answer

Using hash table to store all the jewels, and then count the jewels appeared in string S.

Time Complexity

O(n + m) which n refers to length of J and m refers to length of S.

Code

C++

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        if(J.length() == 0) return 0;
        unordered_set<char> jews;
        for(int i = 0; i < J.length(); ++i)
            jews.insert(J[i]);
        int res = 0;
        for(int i = 0; i < S.length(); ++i)
        {
            if(jews.find(S[i]) != jews.end())
                res++;
        }
        return res;
    }
};