for c in ransomNote: if c in r_hashmap: r_hashmap[ c ] += 1 else: r_hashmap[ c ] = 1
for c in magazine: if c in m_hashmap: m_hashmap[ c ] += 1 else: m_hashmap[ c ] = 1
for a in r_hashmap: if a notin magazine or r_hashmap[a] > m_hashmap[a] : returnFalse returnTrue
優化1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defcanConstruct(self, ransomNote: str, magazine: str) -> bool: m_hashmap = {} for c in magazine: if c in m_hashmap: m_hashmap[ c ] += 1 else: m_hashmap[ c ] = 1
for c in ransomNote: if c notin m_hashmap or m_hashmap[c] - 1 < 0: returnFalse m_hashmap[c] -= 1 returnTrue
看到好的解法
1 2 3 4 5 6 7
classSolution: defcanConstruct(self, ransomNote: str, magazine: str) -> bool: for c inset(ransomNote): if magazine.count(c)<ransomNote.count(c): returnFalse returnTrue