【Leetcode】383. Ransom Note
2017-03-02 09:59
429 查看
方法一:
思路:
(1)使用HashMap,将magazine读取入HashMap,key是字符,value是对应该字符的个数。
(2)遍历ransomNote,对HashMap进行操作,若HashMap中不含有该字符,或当前含有的字符个数个数=0,则说明ransomNote中含有的字符,在magazine中没有覆盖到。
Runtime:71ms
方法二:
思路:
建立2个哈希表r、m,分别统计每个字符出现的次数,最后比较r、m的相应字符出现的次数,若r的大,则返回false。
Runtime:16ms
思路:
(1)使用HashMap,将magazine读取入HashMap,key是字符,value是对应该字符的个数。
(2)遍历ransomNote,对HashMap进行操作,若HashMap中不含有该字符,或当前含有的字符个数个数=0,则说明ransomNote中含有的字符,在magazine中没有覆盖到。
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { Map<Character, Integer> map = new HashMap<Character, Integer>(); int rLen = ransomNote.length(); int mLen = magazine.length(); if (rLen > mLen) return false; for (int i = 0; i < mLen; i++) { char ch = magazine.charAt(i); if (map.containsKey(ch)) map.put(ch, map.get(ch) + 1); else map.put(ch, 1); } for (int i = 0; i < rLen; i++) { char ch = ransomNote.charAt(i); if (!map.containsKey(ch) || map.get(ch) == 0) return false; map.put(ch, map.get(ch) - 1); } return true; } }
Runtime:71ms
方法二:
思路:
建立2个哈希表r、m,分别统计每个字符出现的次数,最后比较r、m的相应字符出现的次数,若r的大,则返回false。
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int rLen = ransomNote.length(); int mLen = magazine.length(); int[] r = new int[26]; int[] m = new int[26]; if (rLen > mLen) return false; for (int i = 0; i < rLen; i++) r[ransomNote.charAt(i) - 'a']++; for (int i = 0; i < mLen; i++) m[magazine.charAt(i) - 'a']++; for (int i = 0; i < 26; i++) { if (r[i] > m[i]) return false; } return true; } }
Runtime:16ms
相关文章推荐
- Leetcode383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note(java)
- leetcode 383. Ransom Note
- LeetCode笔记:383. Ransom Note
- LeetCode-383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note 题解(C++)
- leetcode 383. Ransom Note HashMap 统计字符 + HashMap
- [LeetCode] 383. Ransom Note
- LeetCode_383. Ransom Note
- Leetcode - String - 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
- Leetcode 383. Ransom Note (Easy) (cpp)
- LeetCode 383. Ransom Note