Skip to content

Commit

Permalink
Create count-prefix-and-suffix-pairs-ii.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Feb 20, 2024
1 parent 226d8d8 commit 76cb846
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Python/count-prefix-and-suffix-pairs-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Time: O(n * l)
# Space: O(t)

import collections


# trie
class Solution(object):
def countPrefixSuffixPairs(self, words):
"""
:type words: List[str]
:rtype: int
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
result = 0
for w in words:
curr = trie
for i in xrange(len(w)):
curr = curr[w[i], w[~i]]
result += curr["_cnt"] if "_cnt" in curr else 0
curr["_cnt"] = curr["_cnt"]+1 if "_cnt" in curr else 1
return result

0 comments on commit 76cb846

Please sign in to comment.