Algorithm gems and stones

The given string J represents the type of gem in the stone, and the string S represents the stone you own. Each character in S represents a type of stone you own, and you want to know how many of the stones you own are gems. The letters in J are not repeated, and all the characters in J and S are letters. Letters are case-sensitive, so "a" and "A" are different types of stones.

Example 1:

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

Output: 3

Example 2:

Input: J = "z", S = "ZZ"

Output: 0

note:

S and J can contain up to 50 letters.

The characters in J are not repeated.

Source: LeetCode 771. Gems and Stones
Link: https://leetcode-cn.com/problems/jewels-and-stones/

Algorithm 1: Double for loop

int Fun(string J, string S) {
    
    
	int i = 0;
	for (int j = 0; j < J.length(); j++)
	{
    
    
	for (int s = 0; s < S.length(); s++)
		{
    
    
			if (J[j] == S[s]) 
			i++;
		}
	}
	return i;
}

Algorithm 2: c++ find() function

int numJewelsInStones(string J, string S) {
    
    
	int cnt = 0;
	for (auto s : S)
	{
    
    
		if (find(J.begin(), J.end(), s) != J.end())
		{
    
    
			cnt++;
		}
	}
	return cnt;
}

Algorithm 3: Implement a hash (hash) table, use the hash table to record the types of gems, and traverse again to count the number of gems

int numJewelsInStones2(char * J, char * S)  
{
    
      

    int num = 0;//宝石数量  

    char chars[128] = {
    
    0};//统计J中宝石是否出现,0没有出现,1出现  .hash表

       //遍历J,记录宝石出现的种类  

    while(*J != '\0')  

    {
    
      
        chars[*J++] = 1;  

    }  

    // 遍历石头,统计宝石的个数  

    while(*S != '\0')  

    {
    
      

        if(chars[*S++] == 1)  

        {
    
      

            num++;  

        }  

    }  

       return num;  

} 

Algorithm 4: Use count_if and any_if() functions.
Usage: Usage: bool any_of (InputIterator _First, InputIterator _Last, Predicate _Pred );

int numJewelsInStones(string J, string S) {
    
    
	return count_if(S.begin(), S.end(),
		[&](char ch) {
    
     return any_of(J.begin(), J.end(), [&](char a) {
    
     return a == ch; }); });
}

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109126546