336. Palindrome Pairs
https://leetcode.com/problems/palindrome-pairs/description/
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.
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
Thoughts
在一堆字符串中找出能拼成回文的pair。一个str可以看成l和r两部分,然后可能有两种和其它str拼成回文的方法:rev_r l r和l r rev_l。因此把组内所有reverserd存进hash map中,然后对每一个词遍历所有的划分,看l自身是回文的情况下,map中有没有rev_r;r同理。因为空串的存在,所有的划分包含了null(l) s(r)和s(l) null。 为了避免rev_r null r和l null rev_l 给出重复结果,第二个判断条件加检查l是否为空。
Code
Analysis
时间复杂度O(N).
Last updated
Was this helpful?