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. Python中的类、对象、继承

    类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...

  2. eclipse中Maven运行时报错: -Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.

    1.安装 Maven 如果需要使用到 Maven ,必须首先安装 Maven , Maven 的下载地址在 Apache Maven 中有,您也可以点击这里下载 zip ,tar.gz. 下载好 Ma ...

  3. [C1] C1FlexGrid 排除非绑定列的验证效果

    一.前言 前提是 C1FlexGrid 中存在数据绑定列和自定义列(非数据绑定列),此时如果该行编辑后出现排他错误,自定义列也会出现验证结果的红色边框: 但是自定义列如果只是一些按钮操作,提示说明什么 ...

  4. SHA-256算法

    SHA-.h #ifndef _SHA_256_H #define _SHA_256_H #include<iostream> using namespace std; typedef u ...

  5. 【挖财工作笔记】idea使用指南

    一 安装破解 破解选择服务器,然后选择地址:http://www.iteblog.com/idea/key.php  http://idea.iteblog.com/key.php  http://i ...

  6. js获取页面url

    设置或获取对象指定的文件名或路径. window.location.pathname例:http://localhost:8086/topic/index?topicId=361alert(windo ...

  7. JS正则表达式(JavaScript regular expression)

    RegExp直接量和对象的创建 就像字符串和数字一样,程序中每个取值相同的原始类型直接量均表示相同的值,这是显而易见的.程序运行时每次遇到对象直接量(初始化表达式)诸如{}和[]的时候都会创建新对象. ...

  8. SecutrCRTt 连接VirtualBox 中的Ubuntu -端口转发

    端口转发: 设置>网络>端口转发   端口转发: 子系统地址通过在Linux系统总使用ifconfig查看:   还需要在linux主机上安装sshd sudo apt-get insta ...

  9. office 2010 word每次启动都需要配置

    解决方式: 进入cmd,运行以下命令即可,如果提示已存在,选择Y覆盖就行了 reg add HKCU\Software\Microsoft\Office\14.0\Word\Options /v No ...

  10. Linux安装xwindow图形界面(转载)

    http://jingyan.baidu.com/article/7f766daf42ce984100e1d045.html 1.检查Linux系统是否能够联网. 2.执行命令 yum -y grou ...