LeetCode Solution Summary 771. Gems and Stones

Directory link:

Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog

GitHub synchronous brushing project:

https://github.com/September26/java-algorithms

Link to the original title: Likou


describe:

You are given a string  jewels representing the type of gemstone in the stone, and another string  stones representing the stone you have. stones Each character in represents a type of stone you own, and you want to know how many of the stones you own are gems.

The letters are case sensitive, so  "a" and  "A" are different types of stones.

Example 1:

Input: jewels = "aA", stones = "aAAbbbb"
 Output: 3

Example 2:

Input: jewels = "z", stones = "ZZ"
 Output: 0

hint:

  • 1 <= jewels.length, stones.length <= 50
  • jewels and  stones consist only of English letters
  • jewelsAll  characters in the 

Problem-solving ideas:

Convert the jewels into a set of char type, and then judge whether the char in the stones exists.

code:

class Solution771
{
public:
    int numJewelsInStones(string jewels, string stones)
    {
        set<char> jewelsSet;
        const char *c = jewels.c_str();
        while (*(c) != '\0')
        {
            char cc = *(c);
            jewelsSet.insert(cc);
            c++;
        }
        int num = 0;
        const char *stonesChar = stones.c_str();
        while (*stonesChar != '\0')
        {
            if (jewelsSet.find(*(stonesChar)) != jewelsSet.end())
            {
                num++;
            }
            stonesChar++;
        }
        return num;
    }
};

おすすめ

転載: blog.csdn.net/AA5279AA/article/details/131891612