LeetCode-383. Ransom Note
2017-02-23 17:19
399 查看
问题:https://leetcode.com/problems/ransom-note/?tab=Description
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. 给定一个字符串ransom和一个字符串magazine,判定是否所有ransom中的字符都出现在了magazine里。
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
分析:统计多字母那个字符串中各个字母出现的次数,然后再用ransomNote中字母出现了,就减去1,如果不能包含所有的话,会减到0。
C++代码:
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. 给定一个字符串ransom和一个字符串magazine,判定是否所有ransom中的字符都出现在了magazine里。
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
分析:统计多字母那个字符串中各个字母出现的次数,然后再用ransomNote中字母出现了,就减去1,如果不能包含所有的话,会减到0。
C++代码:
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int lr=ransomNote.length(); int lm=magazine.length(); vector<int> box(128,0); if(lr==0) return true; if(lr>lm) return false; for(char m:magazine){ box[m]++; } for(char r:ransomNote){ if(box[r]==0) return false; box[r]--; } return true; } };
相关文章推荐
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode383. Ransom Note优雅解法(线性时间复杂度)
- 【LeetCode】 383. Ransom Note
- LeetCode 383. Ransom Note 自己的解法
- [leetcode] 383. Ransom Note
- LeetCode—383. Ransom Note
- LeetCode383. Ransom Note
- Leetcode 383. Ransom Note
- [LeetCode]--383. Ransom Note
- [Leetcode] 383. Ransom Note 解题报告
- [leetcode] 383. Ransom Note 解题报告
- leetcode 383. Ransom Note
- leetcode-383. Ransom Note
- <LeetCode OJ> 383. Ransom Note
- LeetCode - 383. Ransom Note
- leetcode 383. Ransom Note 解题报告
- LeetCode 383. Ransom Note
- LeetCode-383. Ransom Note (Java)
- LeetCode 383. Ransom Note