Palindrome Pairs
Solution Code
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
word_dict = {word: i for i, word in enumerate(words)}
res = []
for i, word in enumerate(words):
for j in range(len(word) + 1):
prefix, suffix = word[:j], word[j:]
if prefix == prefix[::-1]:
rev_suffix = suffix[::-1]
if rev_suffix in word_dict and word_dict[rev_suffix] != i:
res.append([word_dict[rev_suffix], i])
if j != len(word) and suffix == suffix[::-1]:
rev_prefix = prefix[::-1]
if rev_prefix in word_dict and word_dict[rev_prefix] != i:
res.append([i, word_dict[rev_prefix]])
return res
