回文对

时间:2018-05-09 02:29:01

标签: algorithm trie

给定一个唯一单词列表,找到给定列表中所有不同索引(i,j)的对,以便两个单词的连接,即单词[i] +单词[j]是回文。< / p>

Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]


How can I solve this using Trie data structure?

1 个答案:

答案 0 :(得分:1)

使用Brute Force,您可以轻松找到 O(N 2 K)中的所有回文,其中 N 是该文字中的单词数list和 K 是为回文检查的最大长度。

使用Trie您可以在 O(NK 2 中获得结果。

Pseduocode

1) Create an empty Trie.
2) Do following for every word:-
    a) Insert reverse of current word.
    b) Also store up to which index it is 
       a palindrome.
3) Traverse list of words again and do following 
   for every word.
    a) If it is available in Trie then return true
    b) If it is partially available
         Check the remaining word is palindrome or not 
         If yes then return true that means a pair
         forms a palindrome.
         Note: Position upto which the word is palindrome
               is stored because of these type of cases.

参考Palindrome Pairs