Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.git
Example 1:github
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:數組
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]app
給定一組惟一的單詞, 找出全部不一樣 的索引對(i, j),使得列表中的兩個單詞, words[i] + words[j] ,可拼接成迴文串。ui
示例 1:code
輸入: ["abcd","dcba","lls","s","sssll"]
輸出: [[0,1],[1,0],[3,2],[2,4]]
解釋: 可拼接成的迴文串爲 ["dcbaabcd","abcddcba","slls","llssssll"]
示例 2:索引
輸入: ["bat","tab","cat"]
輸出: [[0,1],[1,0]]
解釋: 可拼接成的迴文串爲 ["battab","tabbat"]ip
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-04-06 12:11:30 # @Last Modified by: 何睿 # @Last Modified time: 2019-04-07 10:20:01 class Solution: def palindromePairs(self, words: [str]) -> [[int]]: # 結果數組 result = [] # 字典,用於獲取索引 worddict = {word: i for i, word in enumerate(words)} for i, word in enumerate(words): count = len(word) for j in range(count + 1): # 獲取字段的前半部分,後半部分 prefix, subfix = word[:j], word[j:] # 前半部分的反轉,後半部分的反轉 reprefix, resubfix = prefix[::-1], subfix[::-1] # 若是前半部分是 palindrome 而且後半部分的反轉在字典中 if prefix == reprefix and resubfix in worddict: m = worddict[resubfix] # 不能取到字符自己 if m != i: result.append([m, i]) # 若是後半部分是迴文字符串,而且前半部分的逆序在字典中 if j != count and subfix == resubfix and reprefix in worddict: result.append([i, worddict[reprefix]]) return result