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.
题意简单的说,就是要从magazine中挑选出字符构造成ransomNote,每个字符仅能选择一次,不能就返回false。因为仅有26个字母,可以利用额外的cnt数组来记录magazine中每个字母出现的次数,若能构造,则每个cnt记录都应该是大于等于0的。具体代码如下:
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; }
相关文章推荐
- LeetCode oj 383. Ransom Note(哈希)
- <LeetCode OJ> 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- LeetCode 383. Ransom Note
- Leetcode383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- [LeetCode]383. Ransom Note
- LeetCode 383. Ransom Note
- 383. Ransom Note
- LeetCode_383. Ransom Note
- [leetcode]: 383. Ransom Note
- leetcode题解-58. Length of Last Word && 67. Add Binary && 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- LeetCode—383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note