leetcode_336
Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome.
Example 1:
Input: words = ["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: words = ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] Example 3:
Input: words = ["a",""] Output: [[0,1],[1,0]]
Constraints:
1 <= words.length <= 5000 0 <= words[i] <= 300 words[i] consists of lower-case English letters.
Solutions
straight forward O(n2 * len(w))
May got TLE.
class Solution {
public:
bool ispalin(string & s1, string & s2, int i, int j) {
int n1 = s1.size(), n2 = s2.size();
while (i < n1 && j > 0)
if (s1[i++] != s2[--j])
return false;
if (&s1 == &s2)
return true;
else if (i < n1)
return ispalin(s1, s1, i, s1.size());
else if (j > 0)
return ispalin(s2, s2, 0, j);
else
return true;
}
vector<vector<int>> palindromePairs(vector<string>& words) {
int n = words.size();
vector<vector<int>> res;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (ispalin(words[i], words[j], 0, words[j].size()))
res.push_back({i, j});
}
return res;
}
};trie O(mn)
O(mn). m is number of words, n is the average length of each word.For
s1 + s2, len(s1) > len(s2)to be palindrome, we can putrev(s2)into a trie, then for a givens1, we can search for all possibles2such thatrev(s2)equals to a prefix string ofs1inO(len(s1))time.After that, we only need to check if the trailing part of
s1is a palindrome.
For cases when
len(s1) < len(s2), we can treatrev(s2)ass1and put alls1into a trie, then all steps followed are the same as above.Check if a substring is a palindrome can be achieved in
O(n)time when usingManacheralrogithm.
Last updated
Was this helpful?