[leetcode] 383. Ransom Note 解题报告
2016-08-29 14:16
489 查看
题目链接: https://leetcode.com/problems/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.
思路: 一个hash表即可
代码如下:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> hash;
for(auto ch: magazine) hash[ch]++;
for(auto ch: ransomNote)
if(--hash[ch]<0) return false;
return true;
}
};
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
思路: 一个hash表即可
代码如下:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> hash;
for(auto ch: magazine) hash[ch]++;
for(auto ch: ransomNote)
if(--hash[ch]<0) return false;
return true;
}
};
相关文章推荐
- leetcode 383. Ransom Note 解题报告
- [Leetcode] 383. Ransom Note 解题报告
- Leetcode 383. Ransom Note 构造字符串 解题报告
- LeetCode解题报告 383. Ransom Note [easy]
- LeetCode 383. Ransom Note 解题报告
- 【LeetCode】383.Ransom Note(Easy)解题报告
- 【LeetCode】Ransom Note 解题报告
- LeetCode: Populating Next Right Pointers in Each Node II 解题报告
- [Leetcode] 329. Longest Increasing Path in a Matrix 解题报告
- leetcode 148. Sort List 解题报告
- leetcode解题报告:188 Best Time to Buy and Sell Stock IV
- LeetCode—Binary Tree Preorder Traversal 解题报告
- LeetCode: Balanced Binary Tree 解题报告
- [leetcode]136. Single Number@Java解题报告
- [Leetcode] 504. Base 7 解题报告
- LeetCode — Linked List Cycle II 解题报告
- LeetCode 1.Two Sum 解题报告
- Leetcode 400. Nth Digit 第n个数字 解题报告
- 【LeetCode】Arranging Coins 解题报告
- LeetCode: Spiral Matrix 解题报告