[LeetCode]#2068. Check Whether Two Strings are Almost Equivalent
Environment: Python 3.8
Key technique: Counter, |, max
word2 are considered almost equivalent if the differences between the frequencies of each letter from
word2 is at most
Given two strings
word2, each of length
word2 are almost equivalent, or
The frequency of a letter
x is the number of times it occurs in the string.
Input: word1 = "aaaa", word2 = "bccb"
Explanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb".
The difference is 4, which is more than the allowed 3.
- use Counter to word1 and word2
- Find their different
- Find their union
- If value ≤3, return True
def checkAlmostEquivalent(self, word1, word2):
c1, c2 = Counter(word1), Counter(word2)
values = ((c1-c2)|(c2-c1)).values()
return max(values, default=0) < 4
Note: default=0 is for a special case.