classSolution: defcanConstruct(self, ransomNote: str, magazine: str) -> bool: note = [0] * 26 for i in magazine: note[ord(i)-ord('a')] += 1 for i in ransomNote: note[ord(i)-ord('a')] -= 1 if note[ord(i)-ord('a')] < 0: returnFalse returnTrue
ransomNote長度: m magazine長度: n 時間複雜度: O(m+n) 空間複雜度: O(1)
難點
ransomNote與magazine混肴先後關係順序
最佳解法
此為最佳解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
""" 字典 數據量大時,使用list優於dict """ classSolution: defcanConstruct(self, ransomNote: str, magazine: str) -> bool: counts = {} for c in magazine: counts[c] = counts.get(c, 0) + 1 for c in ransomNote: if c notin counts or counts[c] == 0: returnFalse counts[c] -= 1 returnTrue