- 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
Example 1:
Input:
[“bat”, “tab”, “cat”]
Output:
[[0, 1], [1, 0]]
Explanation:
The palindromes are ["battab", "tabbat"]
Example 2:
Input:
[“abcd”, “dcba”, “lls”, “s”, “sssll”]
Output:
[[0, 1], [1, 0], [3, 2], [2, 4]]
Explanation:
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
解法1:
时间复杂度分析:假设字符串的平均长度为k,数组长度为n, 第一层循环为n,第二次循环为k, 判断回文为k,因此复杂度为O(kn^2)
class Solution {
public:
/**
* @param words: a list of unique words
* @return: all pairs of distinct indices
*/
vector<vector<int>> palindromePairs(vector<string> &words) {
int n = words.size();
if (n == 0) return {{}};
vector<vector<int>> result;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
// string concatStr = words[i] + words[j];
if (isPalindrome(words[i] + words[j])) result.push_back({i, j});
// concatStr = words[j] + words[i];
if (isPalindrome(words[j] + words[i])) result.push_back({j, i});
}
}
return result;
}
private:
bool isPalindrome(string s) {
int n = s.size();
int p1 = 0, p2 = n - 1;
while(p1 < p2) {
if (s[p1] != s[p2]) return false;
p1++;
p2--;
}
return true;
}
};
解法2:
时间复杂度分析:假设字符串的平均长度为k,数组长度为n, 第一层循环为n,第二次循环为k, 判断回文为k,因此复杂度为O(nk^2)。
class Solution {
public:
/**
* @param words: a list of unique words
* @return: all pairs of distinct indices
*/
vector<vector<int>> palindromePairs(vector<string> &words) {
int n = words.size();
if (n == 0) return {{}};
vector<vector<int>> result;
unordered_map<string, int> um;
for (int i = 0; i < n; ++i) um[words[i]] = i;
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= words[i].size(); ++j) {
string left = words[i].substr(0, j);
string right = words[i].substr(j);
if (isPalindrome(left)) {
string tmpRight = right;
reverse(tmpRight.begin(), tmpRight.end());
if (um.find(tmpRight) != um.end() && um[tmpRight] != i) {
result.push_back({um[tmpRight], i});
}
}
if (right.size() > 0 && isPalindrome(right)) {
string tmpLeft = left;
reverse(tmpLeft.begin(), tmpLeft.end());
if (um.find(tmpLeft) != um.end() && um[tmpLeft] != i) {
result.push_back({i, um[tmpLeft]});
}
}
}
}
return result;
}
private:
bool isPalindrome(string s) {
int n = s.size();
if (n < 2) return true;
int p1 = 0, p2 = n - 1;
while(p1 < p2) {
if (s[p1] != s[p2]) return false;
p1++;
p2--;
}
return true;
}
};
本文深入探讨了在给定的唯一单词列表中,如何寻找所有可能的索引对,使得两个单词拼接后的字符串形成回文。提供了两种算法实现方案,详细分析了时间复杂度,并附带代码示例。
488

被折叠的 条评论
为什么被折叠?



