- Find All Anagrams in a String
Input:
s: “cbaebabacd” p: “abc”
Output:
[0, 6]
Explanation:
The substring with start index = 0 is “cba”, which is an anagram of “abc”.
The substring with start index = 6 is “bac”, which is an anagram of “abc”.
def findAnagrams_leetcode(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
p_chars = Counter(p)
i = 0
j = len(p)
window = Counter(s[i:j])
results = []
while j <= len(s):
if +window == p_chars:
results.append(i)
window[s[i]] -= 1
if j < len(s):
window[s[j]] += 1
i += 1
j += 1
return results
在上面的算法中,"+windows" 的意思是 複製一個和windows相同的Counter實例,並且過濾掉其中 包含 0和負數的項。
b = {"a": 1, "b": 3, "c": 0, "d": -1}
a = + Counter(b)
print("a:{}".format(a))
# a:Counter({'b': 3, 'a': 1})
“+Counter()” 之所以生效,是因爲Counter 重載了 pos 方法, 實現了一元(unary)操作符 ‘+’ 。
class Counter(Dict[_T, int], Generic[_T]):
...
def __add__(self, other: Counter[_T]) -> Counter[_T]: ...
...
def __pos__(self) -> Counter[_T]: ...
def __neg__(self) -> Counter[_T]: ...
...
Common patterns for working with Counter objects:
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
c += Counter() # remove zero and negative counts