本文主要是介绍336. 回文对(前缀树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Description
给定一组 互不相同 的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
示例 1:输入:["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"]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution 1 暴力枚举
class Solution:def palindromePairs(self, words: List[str]) -> List[List[int]]:def check(s):n = len(s)left, right = 0, n - 1while left < right:if s[left] != s[right]:return Falseleft, right = left + 1, right - 1return Trueans = []for i in range(len(words)):for j in range(i+1, len(words)):if check(words[i]+words[j]):ans.append([i, j])if check(words[j]+words[i]):ans.append([j, i])return ans
Solution 2 前缀树
class Node:def __init__(self):self.ch = [0] * 26self.flag = -1class Solution:def palindromePairs(self, words: List[str]) -> List[List[int]]:tree = [Node()]def insert(s: str, index: int):length = len(s)add = 0for i in range(length):x = ord(s[i]) - ord("a")if tree[add].ch[x] == 0:tree.append(Node())tree[add].ch[x] = len(tree) - 1add = tree[add].ch[x]tree[add].flag = indexdef findWord(s: str, left: int, right: int) -> int:add = 0for i in range(right, left - 1, -1):x = ord(s[i]) - ord("a")if tree[add].ch[x] == 0:return -1add = tree[add].ch[x]return tree[add].flagdef isPalindrome(s: str, left: int, right: int) -> bool:length = right - left + 1return length < 0 or all(s[left + i] == s[right - i] for i in range(length // 2))n = len(words)for i, word in enumerate(words):insert(word, i)ret = list()for i, word in enumerate(words):m = len(word)for j in range(m + 1):if isPalindrome(word, j, m - 1):leftId = findWord(word, 0, j - 1)if leftId != -1 and leftId != i:ret.append([i, leftId])if j and isPalindrome(word, 0, j - 1):rightId = findWord(word, j, m - 1)if rightId != -1 and rightId != i:ret.append([rightId, i])return ret作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/palindrome-pairs/solution/hui-wen-dui-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
这篇关于336. 回文对(前缀树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!