回文对
回文对
给定一组 互不相同 的单词, 找出所有 不同 的索引对 (i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
def f(words):
def isPalindrome(s, i, j):
return s[i:j] == s[i:j][::-1]
data = {word[::-1]:i for i,word in enumerate(words)}
def find(w):
return data.get(w, -1)
ans = []
for i,word in enumerate(words):
for j in range(len(words[i])):
if isPalindrome(word, j, len(word)) and find(word[0:j]) != -1:
ans.append([i, find(word[0:j])])
if isPalindrome(word, 0, j) and find(word[j:]) != -1:
ans.append([find(word[j:]), i])
return ans
words = ["abcd","dcba","lls","s","sssll"]
print(f(words))