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.

这道题给我们了许多单词,让我们找出回文对,就是两个单词拼起来是个回文字符串,我最开始尝试的是brute force的方法,每两个单词都拼接起来然后判断是否是回文字符串,但是通过不了OJ,会超时,可能这也是这道题标为Hard的原因之一吧,那么我们只能找别的方法来做,通过学习大神们的解法,发现如下两种方法比较好,其实两种方法的核心思想都一样,写法略有不同而已,那么我们先来看第一种方法吧,要用到哈希表来建立每个单词和其位置的映射,然后需要一个set来保存出现过的单词的长度,算法的思想是,遍历单词集,对于遍历到的单词,我们对其翻转一下,然后在哈希表查找翻转后的字符串是否存在,注意不能和原字符串的坐标位置相同,因为有可能一个单词翻转后和原单词相等,现在我们只是处理了bat和tab的情况,还存在abcd和cba,dcb和abcd这些情况需要考虑,这就是我们为啥需要用set,由于set是自动排序的,我们可以找到当前单词长度在set中的iterator,然后从开头开始遍历set,遍历比当前单词小的长度,比如abcdd翻转后为ddcba,我们发现set中有长度为3的单词,然后我们dd是否为回文串,若是,再看cba是否存在于哈希表,若存在,则说明abcdd和cba是回文对,存入结果中,对于dcb和aabcd这类的情况也是同样处理,我们要在set里找的字符串要在遍历到的字符串的左边和右边分别尝试,看是否是回文对,这样遍历完单词集,就能得到所有的回文对,参见代码如下:

解法一:

class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
unordered_map<string, int> m;
set<int> s;
for (int i = ; i < words.size(); ++i) {
m[words[i]] = i;
s.insert(words[i].size());
}
for (int i = ; i < words.size(); ++i) {
string t = words[i];
int len = t.size();
reverse(t.begin(), t.end());
if (m.count(t) && m[t] != i) {
res.push_back({i, m[t]});
}
auto a = s.find(len);
for (auto it = s.begin(); it != a; ++it) {
int d = *it;
if (isValid(t, , len - d - ) && m.count(t.substr(len - d))) {
res.push_back({i, m[t.substr(len - d)]});
}
if (isValid(t, d, len - ) && m.count(t.substr(, d))) {
res.push_back({m[t.substr(, d)], i});
}
}
}
return res;
}
bool isValid(string t, int left, int right) {
while (left < right) {
if (t[left++] != t[right--]) return false;
}
return true;
}
};

下面这种方法没有用到set,但实际上循环的次数要比上面多,因为这种方法对于遍历到的字符串,要验证其所有可能的子串,看其是否在哈希表里存在,并且能否组成回文对,anyway,既然能通过OJ,说明还是比brute force要快的,参见代码如下:

解法二:

class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> res;
unordered_map<string, int> m;
for (int i = ; i < words.size(); ++i) m[words[i]] = i;
for (int i = ; i < words.size(); ++i) {
int l = , r = ;
while (l <= r) {
string t = words[i].substr(l, r - l);
reverse(t.begin(), t.end());
if (m.count(t) && i != m[t] && isValid(words[i].substr(l == ? r : , l == ? words[i].size() - r: l))) {
if (l == ) res.push_back({i, m[t]});
else res.push_back({m[t], i});
}
if (r < words[i].size()) ++r;
else ++l;
}
}
return res;
}
bool isValid(string t) {
for (int i = ; i < t.size() / ; ++i) {
if (t[i] != t[t.size() - - i]) return false;
}
return true;
}
};

参考资料:

https://leetcode.com/discuss/91562/my-c-solution-275ms-worst-case-o-n-2

https://leetcode.com/discuss/91531/accepted-short-java-solution-using-hashmap

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Palindrome Pairs 回文对的更多相关文章

  1. [LeetCode] Palindrome Permutation 回文全排列

    Given a string, determine if a permutation of the string could form a palindrome. For example," ...

  2. 336 Palindrome Pairs 回文对

    给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文.示例 1:给定 words = ["bat&quo ...

  3. [LeetCode] Shortest Palindrome 最短回文串

    Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...

  4. [LeetCode] 214. Shortest Palindrome 最短回文串

    Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. ...

  5. [LeetCode] Valid Palindrome 验证回文字符串

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  6. LeetCode Valid Palindrome 有效回文(字符串)

    class Solution { public: bool isPalindrome(string s) { if(s=="") return true; ) return tru ...

  7. LeetCode:验证回文串【125】

    LeetCode:验证回文串[125] 题目描述 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写. 说明:本题中,我们将空字符串定义为有效的回文串. 示例 1: 输入: ...

  8. 前端与算法 leetcode 125. 验证回文串

    目录 # 前端与算法 leetcode 125. 验证回文串 题目描述 概要 提示 解析 解法一:api侠 解法二:双指针 算法 传入测试用例的运行结果 执行结果 GitHub仓库 查看更多 # 前端 ...

  9. CF932G Palindrome Partition(回文自动机)

    CF932G Palindrome Partition(回文自动机) Luogu 题解时间 首先将字符串 $ s[1...n] $ 变成 $ s[1]s[n]s[2]s[n-1]... $ 就变成了求 ...

随机推荐

  1. Web安全相关(一):跨站脚本攻击(XSS)

    简介 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻击者往Web页 ...

  2. MIS性能优化常见问题与方案(辅助项目组性能优化的总结贴)

    最近帮忙公司的几个项目组进行了不同方面的性能优化,发现几个项目都出现了一些共性的问题.这里写一篇文章,总结一下这几类问题,以及其对应的解决方案.方便其它项目组参考.   常见问题一:打开页面非常慢,有 ...

  3. PHP flush()与ob_flush()的区别

    buffer ---- flush()buffer是一个内存地址空间,Linux系统默认大小一般为4096(1kb),即一个内存页.主要用于存储速度不同步的设备或者优先级不同的 设备之间传办理数据的区 ...

  4. JVM调优总结

    堆大小设置JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制:系统的可用虚拟内存限制:系统的可用物理内存限制.32位系统下,一般限制在1.5G~2G:64为操作 ...

  5. 《Web开发中让盒子居中的几种方法》

    一.记录下几种盒子居中的方法: 1.0.margin固定宽高居中: 2.0.负margin居中: 3.0.绝对定位居中: 4.0.table-cell居中: 5.0.flex居中: 6.0.trans ...

  6. handlebars.js的运用与整理

    最近在做部门的技术分享网站,主要是一些文章的列表和演讲信息展示,内容比较规律,复用性较高.同事推荐了 handlebars.js.用来看看. handlebars.js是一种静态JS模板,用起来还蛮简 ...

  7. Linux Distribution / ROM

    Linux发行版 http://unix.stackexchange.com/questions/87011/how-to-easily-build-your-own-linux-distro 这个文 ...

  8. iOS之数字的格式化

    //通过NSNumberFormatter,同样可以设置NSNumber输出的格式.例如如下代码: NSNumberFormatter *formatter = [[NSNumberFormatter ...

  9. Json解析工具的选择

    前言 前段时间@寒江不钓同学针对国内Top500和Google Play Top200 Android应用做了全面的分析(具体分析报告见文末的参考资料),其中有涉及到对主流应用使用json框架Gson ...

  10. 使用gulp解决RequireJS项目前端缓存问题(一)

    1.前言 前端缓存一直是个令人头疼的问题,你有可能见过下面博客园首页的资源文件链接: 有没有发现文件名后面有一串不规则的东东,没错,这就是运用缓存机制,我们今天研究的就是这种东西. 先堵为快,猛戳链接 ...