您的位置:首页 > 其它

383. Ransom Note

2017-03-20 23:06 197 查看
题目:

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

链接:https://leetcode.com/problems/ransom-note/#/description

3/20/2017

1 public class Solution {
2     public boolean canConstruct(String ransomNote, String magazine) {
3         HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
4         HashMap<Character, Integer> hs = new HashMap<Character, Integer>();
5
6         for (int i = 0; i < magazine.length(); i++) {
7             if (hm.containsKey(magazine.charAt(i))) {
8                 hm.put(magazine.charAt(i), hm.get(magazine.charAt(i)) + 1);
9             } else {
10                 hm.put(magazine.charAt(i), 1);
11             }
12         }
13         for (int i = 0; i < ransomNote.length(); i++) {
14             if (hs.containsKey(ransomNote.charAt(i))) {
15                 hs.put(ransomNote.charAt(i), hs.get(ransomNote.charAt(i)) + 1);
16             } else {
17                 hs.put(ransomNote.charAt(i), 1);
18             }
19         }
20         for (HashMap.Entry<Character, Integer> entry : hs.entrySet()) {
21             Character key = entry.getKey();
22             Integer value = entry.getValue();
23             if (!hm.containsKey(key) || hm.get(key) < value) return false;
24         }
25         return true;
26     }
27 }


别人不用hashmap只用array的解法:

https://discuss.leetcode.com/topic/53864/java-o-n-solution-easy-to-understand/10

Python的Collections.counter的解法:

1 def canConstruct(self, ransomNote, magazine):
2     return not collections.Counter(ransomNote) - collections.Counter(magazine)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: