336. Palindrome Pairs
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了336. 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:
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"]
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
解题思路:
我一开始的想法是把所有单词根据其最后一个字符存入hash表,构成一个<char, vector<string>>的map
然后再遍历每一个单词,根据他们第一个单词在hash表中寻找,构成新的字符串,来判断是否为回文,若是则要加入。
但是这个方法耗时很大,若n为数组长度,k为字符串平聚长度。 应为n*(n-1)*2k
还有一种方法是O(n*k2) n 为数组长度,而k为字符串的平均长度。
这里需要额外注意的是!
字符串数组中!有没有肯恩含有空数组!!!
代码:
我的:
class Solution { public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> ret; unordered_map<string, int> m; unordered_map<char, vector<string>> endWith; bool emptyExist = false; for(int i = 0; i < words.size(); i++){ m[words[i]] = i; if(words[i] != "") endWith[words[i].back()].push_back(words[i]); else emptyExist = true; } for(int i = 0; i < words.size(); i++){ if(emptyExist && words[i] != ""){ if(isPalindrome(words[i])){ ret.push_back({m[""], i}); ret.push_back({i, m[""]}); } } for(auto str : endWith[words[i][0]]){ string newS = words[i] + str; if(m[str] != i && isPalindrome(newS)){ ret.push_back({i, m[str]}); } } } return ret; } bool isPalindrome(string s){ int l = 0, r = s.size()-1; while(l < r){ if(s[l++] != s[r--]) return false; } return true; } };
快的:
class Solution { public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> ret; unordered_map<string, int> dict; for(int i = 0; i < words.size(); i++){ string w = words[i]; reverse(w.begin(), w.end()); dict[w] = i; } if(dict.count("") != 0){ for(int i = 0; i < words.size(); i++){ if(words[i] != ""){ if(isPalindrome(words[i])) ret.push_back({dict[""], i}); } } } for(int i = 0; i < words.size(); i++){ for(int j = 0; j < words[i].size(); j++){ string left = words[i].substr(0, j); string right = words[i].substr(j, words[i].size() - j); if(dict.count(left) != 0 && isPalindrome(right) && dict[left] != i) ret.push_back({i, dict[left]}); if(dict.count(right) != 0 && isPalindrome(left) && dict[right] != i) ret.push_back({dict[right], i}); } } return ret; } bool isPalindrome(string s){ int l = 0, r = s.size()-1; while(l < r){ if(s[l++] != s[r--]) return false; } return true; } };
以上是关于336. Palindrome Pairs的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 336. Palindrome Pairs(回文对)
java 336. Palindrome Pairs(Trie).java
java 336. Palindrome Pairs(Trie).java