LeetCode-383. Ransom Note
2018-03-05 19:31
309 查看
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. 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
Solution 1(C++)
class Solution { public: bool canConstruct(string ransomNote, string magazine) { unordered_map<char, int> count; for(int i=0; i<ransomNote.size(); i++){ count[ransomNote[i]]++; } for(int j=0; j<magazine.size(); j++){ count[magazine[j]]--; } for(auto c:count){ if(c.second>0){ return false; } } return true; } };
Solution 2(C++)
class Solution { public: bool canConstruct(string ransomNote, string magazine) { unordered_map<char, int> map(26); for (int i = 0; i < magazine.size(); ++i) ++map[magazine[i]]; for (int j = 0; j < ransomNote.size(); ++j) if (--map[ransomNote[j]] < 0) return false; return true; } };
算法分析
这道题的算法实现比较简单。不啰嗦。程序分析
解法二与解法一的代码更简洁的地方就是将解法一中额外的检查map中与第二次for循环结合起来了。相关文章推荐
- LeetCode 383. Ransom Note
- [leetcode]: 383. Ransom Note
- leetcode题解-58. Length of Last Word && 67. Add Binary && 383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note
- leetCode 383. Ransom Note 字符串
- LeetCode-Easy部分中标签为String 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 383. Ransom Note HashMap 统计字符 + HashMap
- leetcode_383. Ransom Note-近似子串问题
- leetcode 383. Ransom Note
- LeetCode笔记:383. Ransom Note