LeetCode·每日一题·771. 宝石与石头·哈希

作者:小迅
链接:https://leetcode.cn/problems/jewels-and-stones/solutions/2356302/ha-xi-zhu-shi-chao-ji-xiang-xi-by-xun-ge-jnmr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目

思路

题意 -> 给定一个字符串,求另外一个字符串中字符与给定字符串中相同的个数。

用数组实现哈希表功能,将给定字符串中的所有字符都提取并使用数组记录起来,枚举目标字符串中的每一个字符,与哈希数组进行对比,如果当前字符在哈希数组中有记录,那么字符个数 +1。最后返回记录值即可。

代码注释超级详细

代码


int numJewelsInStones(char * jewels, char * stones){
    char hash[255] = {0};//哈希数组
    int count = 0;
    for (int i = 0; i < strlen(jewels); ++i) {//枚举给定字符串
        hash[jewels[i] - '0']++;//记录字符
    }
    for (int i = 0; i < strlen(stones); ++i) {//枚举目标字符串
        if (hash[stones[i] - '0']) ++count;//记录有效值
    }
    return count;
}

作者:小迅
链接:https://leetcode.cn/problems/jewels-and-stones/solutions/2356302/ha-xi-zhu-shi-chao-ji-xiang-xi-by-xun-ge-jnmr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/m0_64560763/article/details/131888729