|
| 1 | +class Solution: |
| 2 | + def countPrefixSuffixPairs(self, words: List[str]) -> int: |
| 3 | + # Bidirectional as in from both sides of the string |
| 4 | + # key = (x, y) --> x = ith char from front |
| 5 | + # --> y = ith char from end |
| 6 | + # Goes full length of string so the chars cross |
| 7 | + bidirectionalTrie = {} |
| 8 | + for i, word in enumerate(words) : |
| 9 | + curr = bidirectionalTrie |
| 10 | + for j in range(len(word)) : |
| 11 | + key = (word[j], word[len(word) - j - 1]) |
| 12 | + if key not in curr : |
| 13 | + curr[key] = {} |
| 14 | + curr = curr[key] |
| 15 | + |
| 16 | + if False not in curr : |
| 17 | + curr[False] = [] |
| 18 | + curr[False].append(i) |
| 19 | + |
| 20 | + |
| 21 | + # Finding if the current word works as a prefix/suffix |
| 22 | + # of any word |
| 23 | + counter = 0 |
| 24 | + for i, word in enumerate(words) : |
| 25 | + curr = bidirectionalTrie |
| 26 | + |
| 27 | + for j in range(len(word)) : |
| 28 | + key = (word[j], word[len(word) - j - 1]) |
| 29 | + if key not in curr : |
| 30 | + continue |
| 31 | + curr = curr[key] |
| 32 | + |
| 33 | + counter += self.validWords(curr, i) |
| 34 | + |
| 35 | + return counter |
| 36 | + |
| 37 | + |
| 38 | + def validWords(self, trie: dict, lowerBoundIndx: int) -> int : |
| 39 | + if not trie : |
| 40 | + return 0 |
| 41 | + |
| 42 | + # lowerBoundIndx + 1 cause we don't want to match a |
| 43 | + # word with itself. Plus, if it was equal, bisect_left/right |
| 44 | + # would give us the leftmost or rightmost of its own value if |
| 45 | + # it exists. We want the indx of the first greater than it |
| 46 | + # so +1 bisect left will make it the next bigger no matter what |
| 47 | + output = 0 |
| 48 | + if False in trie : |
| 49 | + indxSplit = bisect_left(trie[False], lowerBoundIndx + 1) |
| 50 | + if indxSplit < len(trie[False]) : |
| 51 | + output += len(trie[False]) - indxSplit |
| 52 | + |
| 53 | + for k, v in trie.items() : |
| 54 | + if k : |
| 55 | + output += self.validWords(v, lowerBoundIndx) |
| 56 | + |
| 57 | + return output |
0 commit comments