zoukankan      html  css  js  c++  java
  • 383. 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.

    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)
  • 相关阅读:
    linux 从入门到跑路-目录结构的理解
    linux 从入门到跑路-ls,cp,mkdir命令练习
    linux 从入门到跑路-电源管理
    java 图形界面 Socket编程
    java 图形界面 mvc模式控制
    java 邮件
    java 图形界面
    java 文件的基本操作
    java基础算法题
    java 字符串
  • 原文地址:https://www.cnblogs.com/panini/p/6592191.html
Copyright © 2011-2022 走看看