问题描述
给定一组 互不相同 的单词, 找出所有 不同 的索引对 (i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
示例 1:
输入:words = ["abcd","dcba","lls","s","sssll"]
输出:[[0,1],[1,0],[3,2],[2,4]]
解释:可拼接成的回文串为 ["dcbaabcd","abcddcba","slls","llssssll"]
示例 2:
输入:words = ["bat","tab","cat"]
输出:[[0,1],[1,0]]
解释:可拼接成的回文串为 ["battab","tabbat"]
示例 3:
输入:words = ["a",""]
输出:[[0,1],[1,0]]
提示:
1 <= words.length <= 5000
0 <= words[i].length <= 300
words[i] 由小写英文字母组成
问题求解
很好的一条思维题。
对于任意一个words[i],如果他串联一个短串,那么分割点比在words[i]内,那么只需要判断前缀的反转是否等于短串 + 后缀是否为回文即可。如果串联一个长串,同理。
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
res = []
record = {}
for i, word in enumerate(words):
record[word] = i
words.sort(key=lambda x: len(x))
used = set()
for word in words:
for i in range(len(word) + 1):
prev = word[0:i]
post = word[i:]
if prev[::-1] in used and post[::-1] == post:
res.append([record[word], record[prev[::-1]]])
if post[::-1] in used and prev[::-1] == prev:
res.append([record[post[::-1]], record[word]])
used.add(word)
return res
`
标签:word,336,record,words,post,prev,回文
From: https://www.cnblogs.com/hyserendipity/p/16753335.html