您的位置:首页 > 其它

LeetCode: Ransom Note

2016-08-17 18:06 363 查看

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.bool canConstruct(char* ransomNote, char* magazine) {

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


源代码:

bool canConstruct(char* ransomNote, char* magazine) {

int len1 = strlen(ransomNote);
int len2 = strlen(magazine);

if (len1 > len2) return false;

int sl1[26];
int sl2[26];

for (int i = 0; i < 26; ++i) {
sl1[i] = 0;
sl2[i] = 0;
}
for (int i = 0; i < len1; ++i) {
sl1[ransomNote[i] - 'a']++;
}
for (int i = 0; i < len2; ++i) {
sl2[magazine[i] - 'a']++;
}
for (int i = 0; i < 26; ++i) {
if (sl1[i] > sl2[i]) return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息