您的位置:首页 > 其它

LeetCode OJ-383. Ransom Note

2016-08-12 12:19 344 查看
383. Ransom Note

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

题意简单的说,就是要从magazine中挑选出字符构造成ransomNote,每个字符仅能选择一次,不能就返回false。因为仅有26个字母,可以利用额外的cnt数组来记录magazine中每个字母出现的次数,若能构造,则每个cnt记录都应该是大于等于0的。具体代码如下:
bool canConstruct(char* ransomNote, char* magazine) {
int flag = 1;
int i;
int cnt[27] = { 0 };
for (i = 0; i < strlen(magazine); ++i) {
++cnt[(int) (magazine[i] - 'a') + 1];
}

for (i = 0; i < strlen(ransomNote); ++i) {
if (--cnt[(int) (ransomNote[i] - 'a') + 1] < 0) {
flag = 0;
break;
}
}

return flag;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息