# Leetcode 336. Palindrome Pairs

## 2. Solution

• Version 1
```class Solution:
def palindromePairs(self, words):
result = []
length = len(words)
for i in range(length):
for j in range(i + 1, length):
positive = words[i] + words[j]
reverse = words[j] + words[i]
if self.checkPalindrome(positive):
result.append([i, j])
if self.checkPalindrome(reverse):
result.append([j, i])
return result

def checkPalindrome(self, word):
i = 0
j = len(word) - 1
while i < j:
if word[i] != word[j]:
return False
i += 1
j -= 1
return True```
• Version 2
```class Solution:
def palindromePairs(self, words):
result = []
stat = {}
for index, word in enumerate(words):
stat[word] = index

for index, word in enumerate(words):
length = len(word)
if length == 1 and '' in stat:
result.append([index, stat['']])
result.append([stat[''], index])
continue
for i in range(length + 1):
prefix = word[:i]
rest = word[i:]
reverse = rest[::-1]
if self.checkPalindrome(prefix):
if reverse in stat and index != stat[reverse]:
res = [stat[reverse], index]
if res not in result:
result.append(res)

suffix = word[i:]
rest = word[:i]
reverse = rest[::-1]
if self.checkPalindrome(suffix):

if reverse in stat and index != stat[reverse]:
res = [index, stat[reverse]]
if res not in result:
result.append(res)

return result

def checkPalindrome(self, word):
i = 0
j = len(word) - 1
while i < j:
if word[i] != word[j]:
return False
i += 1
j -= 1
return True```

## Reference

1. https://leetcode.com/problems/palindrome-pairs/

0 条评论

• ### CodeForces 17E Palisection(回文树)

E. Palisection time limit per test 2 seconds memory limit per test 128 meg...

• ### Leetcode 题目列表（难度、出现频率、知识点）

不全，但好像没看到有更好的版本，刷前132题暂时凑合着用吧！ 转载自：LeetCode Question Difficulty Distribution ?...

• ### LeetCode-9. Palindrome Number | 回文数

Given an integer x, return true if x is palindrome integer.

• ### HDU 5157 Harry and magic string(回文树)

Harry and magic string Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: ...

• ### LeetCode-Longest Palindromic Substring

LeetCode第5道题目：5. Longest Palindromic Substring

• ### LeetCode 分类刷题 —— Linked List

最近有朋友问我怎么没有更新文章了，因为最近有空的时候都在刷 LeetCode，零零星星刷了快 2 个月了，也累积了不少题目了，所以最近打算把做的几百道题归类，总...

• ### 【LeetCode 409】 关关的刷题日记31Longest Palindrome

关关的刷题日记31 – Leetcode 409. Longest Palindrome 题目 Given a string which consists o...

• ### LeetCode刷题指南（字符串）

文章链接：https://github.com/CyC2018/CS-Notes/blob/master/docs/notes/Leetcode%20%E9%A...

• ### 算法养成记：回文数判断

Determine whether an integer is a palindrome. An integer is a palindrome when it...