336. 回文对
336. 回文对
**class Solution:def palindromePairs(self, words: List[str]) -> List[List[int]]:dic = {w: i for i,w in enumerate(words)}res = []for index, s in enumerate(words):for j in range(len(s)+1):if s[j:] == s[j:][::-1]: if s[:j][::-1] in dic and dic[s[:j][::-1]] != index and [index,dic[s[:j][::-1]]] not in res:res.append([index,dic[s[:j][::-1]]])if s[:j] == s[:j][::-1]:if s[j:][::-1] in dic and dic[s[j:][::-1]] != index and [dic[s[j:][::-1]],index] not in res:res.append([dic[s[j:][::-1]],index])return res**
前缀和后缀
这里的逻辑是如果前缀和后缀里如果有回文对,只要去words里找有没有剩余部分的反转部分,这样两个加在一起就是,反转+回文的前缀+剩余部分 以及 剩余部分+回文的后缀+反转,连起来一整个就都是回文串了。
具体例子
例子:‘abcd’
前缀:‘’, ‘a’, ‘ab’, ‘abc’, ‘abcd’
后缀:‘’, ‘d’, ‘cd’, ‘bcd’, ‘abcd’
这里反转和自己一样的就只有空的和单个字母的,那么我们要去找的就是
前缀:‘’找‘dcba’就可以拼成‘abcddcba’; ‘a’找’dcb’可以拼成‘dcbabcd’
后缀:‘’找‘abcd’就可以拼成‘abcddcba’; ‘d’找’cba’可以拼成‘abcdcba’