ransomNote

Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 



Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
solution with C

思路:因为题目中的字符串全是小写,可以设置一个26个元素的数组int map[26]用来保存对应字母在magazine字串中出现的次数,map[0]代表‘a'在magazine中出现的次数.....map[25]代表'z'在magazine中出现的次数,这些可以在遍历magazine的时候实现,ok,在对ransomNote进行遍历,此时对每个在ransomNote中的字符对应的map的位置进行-1操作,最后判断map里面是否有<0的数字,即可返回true or false

bool canConstruct(char* ransomNote, char* magazine) {
	if (strlen(ransomNote)>strlen(magazine))
		return false;
	int map[26] = { 0 };
	char* p = magazine;
	for (int i = 0; i != strlen(magazine); ++i)
	{
		map[*p - 'a'] += 1;
		++p;
	}
	p = ransomNote;
	for (int i = 0; i != strlen(ransomNote); ++i)
	{
		map[*p - 'a'] -= 1;
		if (map[*p - 'a']<0)
			return false;
		++p;
	}
	return true;
}














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值