336.Palindrome-Pairs

336. Palindrome Pairs

题目地址

https://leetcode.com/problems/palindrome-pairs/

题目描述

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:
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"]

代码

Approach #1 Brute force

Time Complexity : O(n^2*k) // and k be the length of the longest word.

Approach #2 Hashing

Time: O(k^2 * n) Space: O((k+n)^2)

Three Cases:

  1. Check if the reverse of word is present. If it is, then we have a case 1 pair by appending the reverse onto the end of word.

  2. For each suffix of word, check if the suffix is a palindrome. if it is a palindrome, then reverse the remaining prefix and check if it's in the list. If it is, then this is an example of case 2.

  3. For each prefix of word, check if the prefix is a palindrome. if it is a palindrome, then reverse the remaining suffix and check if it's in the list. If it is, then this is an example of case 3.

Approach #3 Using a Trie

Last updated

Was this helpful?