class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
def isPrefixAndSuffix(s1, s2):
if len(s1) > len(s2):
return False
for i in range(len(s1)):
if s1[i] != s2[i]:
return False
j = 0
for i in range(len(s2) - len(s1), len(s2)):
if s1[j] != s2[i]:
return False
j += 1
return True
res = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
res += isPrefixAndSuffix(words[i], words[j])
return resWhere is the size of the input array , and is the maximum length of a string.
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
res = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
w1, w2 = words[i], words[j]
if w2.startswith(w1) and w2.endswith(w1):
res += 1
return resWhere is the size of the input array , and is the maximum length of a string.
class TrieNode:
def __init__(self):
self.children = {}
self.count = 0
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, w: str) -> None:
cur = self.root
for c1, c2 in zip(w, reversed(w)):
if (c1, c2) not in cur.children:
cur.children[(c1, c2)] = TrieNode()
cur = cur.children[(c1, c2)]
cur.count += 1
def count(self, w: str) -> int:
cur = self.root
for c1, c2 in zip(w, reversed(w)):
if (c1, c2) not in cur.children:
return 0
cur = cur.children[(c1, c2)]
return cur.count
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
res = 0
root = Trie()
for w in reversed(words):
res += root.count(w)
root.add(w)
return resWhere is the size of the input array , and is the maximum length of a string.