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) {
源代码:
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;
}
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;
}
相关文章推荐
- [LeetCode-383]Ransom Note(java)
- LeetCode(383)Ransom Note
- LeetCode : Ransom Note
- LeetCode: Ransom Note
- leetcode[Ransom Note]//待整理多种解法
- leetcode383: Ransom Note
- 【LeetCode】383 Ransom Note(java)
- LeetCode之Ransom Note (Java+C)
- LeetCode Ransom Note(字符串)
- LeetCode:Ransom Note_383
- 【Leetcode】Ransom Note
- LeetCode--No.383--Ransom Note
- Leetcode 383 Ransom Note
- Leetcode:383.Ransom Note(统计每个字符串每个字母的个数)
- leetcode: Ransom Note
- LeetCode[383] Ransom Note
- leetcode之Ransom Note
- LeetCode:383 Ransom Note
- 【python】【leetcode】【算法题目383—Ransom Note】
- 【LeetCode】383 Ransom Note(java)