leetcode 336. 回文对

给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文。

示例 1:
给定 words = ["bat", "tab", "cat"]
返回 [[0, 1], [1, 0]]
回文是 ["battab", "tabbat"]

示例 2:
给定 words = ["abcd", "dcba", "lls", "s", "sssll"]
返回 [[0, 1], [1, 0], [3, 2], [2, 4]]
回文是 ["dcbaabcd", "abcddcba", "slls", "llssssll"]`

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
class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def is_reverse(word):
return word==word[::-1]

words = {word:k for k,word in enumerate(words)}
res = []
for word,k in words.iteritems():
n = len(word)
for i in range(n+1):
pre = word[:i]
suf = word[i:]
if is_reverse(pre):
back = suf[::-1]
if back != word and back in words:
res.append([words[back],k])
if i != n and is_reverse(suf):
back = pre[::-1]
if back != word and back in words:
res.append([k,words[back]])
return res