Java Map solution


  • 16
    Q
     public boolean canConstruct(String ransomNote, String magazine) {
            Map<Character, Integer> magM = new HashMap<>();
            for (char c:magazine.toCharArray()){
                int newCount = magM.getOrDefault(c, 0)+1;
                magM.put(c, newCount);
            }
            for (char c:ransomNote.toCharArray()){
                int newCount = magM.getOrDefault(c,0)-1;
                if (newCount<0)
                    return false;
                magM.put(c, newCount);
            }
            return true;
        }
    

  • 4

    Cool use of getOrDefault() :-)


  • 1

    said in Java Map solution:

    char c:magazine.toCharArray()

    This is a little difficult to me.


  • 0
    X

    Another approach is replacing getOrDefault with compute:

    public boolean canConstruct(String ransomNote, String magazine) {
        // final Multiset<Character> occurrences = CharStream.from(magazine).boxed().collect(Collectors.toMultiset());
        // return CharStream.from(ransomNote).boxed().forEach2(e -> occurrences.getAndRemove(e) > 0);
    
        final Map<Character, Integer> magM = new HashMap<>();
    
        for (char c : magazine.toCharArray()) {
            magM.compute(c, (k, v) -> v == null ? 1 : v + 1);
        }
    
        for (char c : ransomNote.toCharArray()) {
            if (magM.compute(c, (k, v) -> v == null ? -1 : v - 1) < 0) {
                return false;
            }
        }
    
        return true;
    }
    

  • 0
    Z
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.