-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#336 Palindrome Pairs.py
33 lines (28 loc) · 1.12 KB
/
#336 Palindrome Pairs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
""" #336 Palindrome Pairs
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the
concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
"""
class Solution:
def palindromePairs(self, words: [str]) -> [[int]]:
def is_palindrome(check):
return check == check[::-1]
words = {word: i for i, word in enumerate(words)}
valid_pals = []
for word, k in words.items():
n = len(word)
for j in range(n+1):
pref = word[:j]
suf = word[j:]
if is_palindrome(pref):
back = suf[::-1]
if back != word and back in words:
valid_pals.append([words[back], k])
if j != n and is_palindrome(suf):
back = pref[::-1]
if back != word and back in words:
valid_pals.append([k, words[back]])
return valid_pals
# test solution
solution = Solution()
words = ["abcd", "dcba", "lls", "s", "sssll"]
print(solution.palindromePairs(words))