May LeetCoding Challenge3 之 HashMap的使用

Map是一种key-value映射表。不存在重复的key。

经常用的方法有put(key,value),get(key),containsKey(key),可以通过for each遍历keyset(),entryset()。

给map赋值的方法可以参考该语句:map.put(c, map.getOrDefault(c, 0)+1);

本题提供两种解法:

1.好理解的方法。遍历ransomNote的字符,找出字符在magazine的下标位置,如果下标为-1(即magazine不存在该字符),返回false;否则删除magazine中该字符。

2.用HashMap存储字符和字符出现的次数。先将magazine存入map,然后再遍历ransomNote,减去字符出现的次数。如果次数小于0,返回false。

 

JAVA

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        for(char c: ransomNote.toCharArray()){
            int index = magazine.indexOf(c);
            if(index == -1) return false;
            magazine = magazine.substring(0, index) + magazine.substring(index+1);
        }
        return true;
    }
}

 

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap<>();
        for(char c: magazine.toCharArray()){
            map.put(c, map.getOrDefault(c, 0)+1);
        }
        for(char c: ransomNote.toCharArray()){
            map.put(c, map.getOrDefault(c, 0)-1);
            if(map.get(c) < 0) return false;
        }
        return true;
    }
}

 

Python3

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        for c in ransomNote:
            if c not in magazine:
                return False
            index = magazine.index(c)
            magazine = magazine[0:index] + magazine[index+1:]
        return True

 

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        d = dict()
        for c in magazine:
            if c in d:
                d[c] += 1
            else:
                d[c] = 1
        for c in ransomNote:
            if c in d:
                d[c] -= 1
            else:
                d[c] = -1
            if d[c] < 0:
                return False
        return True

 

posted @ 2020-05-04 19:11  yawenw  阅读(139)  评论(0编辑  收藏  举报