Leetcode学习笔记:#771 Jewels and Stones

此博客是Leetcode #771 Jewels and Stones的学习笔记。题目给出代表宝石类型的字符串J和代表拥有石头的字符串S,要计算拥有的石头中有多少是宝石。实现思路是两次遍历,第一次将S的字符存入charToFreq并计数,第二次将相同字符对应的值累加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode学习笔记:#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”.

实现:

public int numJewlsInStones(String J, String S){
	if(J.length() == 0 || S.length() == 0){
		return 0;
	}

	int[] charToFreq = new int[256];
	for(char ch:S.toCharArray()){
		charToFreq[ch]++;
	}
	int numJewels = 0;
	for(char ch:J.toCharArray()){
		if(charToFreq[ch] > 0){
			numJewels += charToFreq[ch];
		}
	}
	return numJewels;
}

思路:
两次遍历。第一次遍历把S的每个char遍历进charToFreq,按ASCII码分配,每有一个相同的char便加1,第二次遍历每发现一个相同的char,便把charToFreq中该char相对应的value加入numJewels中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值