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:

Input: ["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: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
 

Approach #1: C++.

class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
int size = words.size();
int mul = 1000000007; int max_len = 0;
vector<vector<int>> hash_pre(size, vector<int>());
vector<vector<int>> hash_suf(size, vector<int>()); vector<int> temp(2, 0);
vector<vector<int>> ret; for (int i = 0; i < size; ++i) {
hash_pre[i] = vector<int>(words[i].size(), 0);
hash_suf[i] = vector<int>(words[i].size(), 0); if (words[i].size() == 0) continue;
hash_pre[i][0] = words[i][0];
hash_suf[i][words[i].size()-1] = words[i][words[i].size()-1];
for (int j = 1; j < words[i].size(); ++j) {
hash_pre[i][j] = hash_pre[i][j-1] * mul + words[i][j];
}
for (int j = (int)words[i].size()-2; j >= 0; --j) {
hash_suf[i][j] = hash_suf[i][j+1] * mul + words[i][j];
}
max_len = max(max_len, (int)words[i].size());
} vector<int> exp(max_len + 1, 0);
exp[0] = 1;
for (int i = 1; i <= max_len; ++i)
exp[i] = exp[i-1] * mul;
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j) {
if (i == j) continue;
int len = words[i].size() + words[j].size();
int hash_left = 0, hash_right = 0;
int left_len = len / 2; if (left_len != 0) {
if (words[i].size() >= left_len) {
hash_left = hash_pre[i][left_len-1];
} else {
if (words[i].size() == 0)
hash_left = hash_pre[j][left_len-1];
else {
int right_pre = left_len - words[i].size();
hash_left = hash_pre[i][words[i].size() - 1] * exp[right_pre] + hash_pre[j][right_pre-1];
}
}
} if (left_len != 0) {
if (words[j].size() >= left_len) {
hash_right = hash_suf[j][words[j].size()-left_len];
} else {
if (words[j].size() == 0)
hash_right = hash_suf[i][words[i].size()-left_len];
else {
int left_pre = left_len - words[j].size();
hash_right = hash_suf[j][0] * exp[left_pre] + hash_suf[i][words[i].size()-left_pre];
}
}
} if (hash_left == hash_right) {
temp[0] = i, temp[1] = j;
ret.push_back(temp);
} }
return ret;
}
};

Runtime: 816 ms, faster than 3.13% of C++ online submissions for Palindrome Pairs.

Approach #2: Java.

class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
Map<String, Integer> index = new HashMap<>();
Map<String, Integer> revIndex = new HashMap<>();
String[] revWords = new String[words.length];
for (int i = 0; i < words.length; ++i) {
String s = words[i];
String r = new StringBuilder(s).reverse().toString();
index.put(s, i);
revIndex.put(r, i);
revWords[i] = r;
}
List<List<Integer>> result = new ArrayList<>();
result.addAll(findPairs(words, revWords, revIndex, false));
result.addAll(findPairs(revWords, words, index, true));
return result;
} private static List<List<Integer>> findPairs(String[] words, String[] revWords, Map<String, Integer> revIndex, boolean reverse) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < words.length; ++i) {
String s = words[i];
for (int k = reverse ? 1 : 0; k <= s.length(); ++k) {
Integer j = revIndex.get(s.substring(k));
if (j != null && j != i) {
if (s.regionMatches(0, revWords[i], s.length() - k, k)) {
result.add(reverse ? Arrays.asList(i, j) : Arrays.asList(j, i));
}
}
}
}
return result;
}
}

  

Approach #3: Python.

class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
wordict = {}
res = []
for i in range(len(words)):
wordict[words[i]] = i
for i in range(len(words)):
for j in range(len(words[i])+1):
tmp1 = words[i][:j]
tmp2 = words[i][j:]
if tmp1[::-1] in wordict and wordict[tmp1[::-1]] != i and tmp2 == tmp2[::-1]:
res.append([i, wordict[tmp1[::-1]]])
if j != 0 and tmp2[::-1] in wordict and wordict[tmp2[::-1]] != i and tmp1 == tmp1[::-1]:
res.append([wordict[tmp2[::-1]], i]) return res

  

Time Submitted Status Runtime Language
a few seconds ago Accepted 144 ms java
27 minutes ago Accepted 864 ms python
3 hours ago Accepted 816 ms cpp

336. Palindrome Pairs(can't understand)的更多相关文章

  1. LeetCode 336. Palindrome Pairs

    原题链接在这里:https://leetcode.com/problems/palindrome-pairs/ 题目: Given a list of unique words, find all p ...

  2. 【LeetCode】336. Palindrome Pairs 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 HashTable 相似题目 参考资料 日期 题目地 ...

  3. leetcode@ [336] Palindrome Pairs (HashMap)

    https://leetcode.com/problems/palindrome-pairs/ Given a list of unique words. Find all pairs of dist ...

  4. 336 Palindrome Pairs 回文对

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

  5. 【leetcode】336. Palindrome Pairs

    题目如下: 解题思路:对于任意一个word,要找出在wordlist中是否存在与之能组成回文的其他words,有两种思路.一是遍历wordlist:二是对word本身进行分析,找出能组成回文的word ...

  6. DP VK Cup 2012 Qualification Round D. Palindrome pairs

    题目地址:http://blog.csdn.net/shiyuankongbu/article/details/10004443 /* 题意:在i前面找回文子串,在i后面找回文子串相互配对,问有几对 ...

  7. 【题解】Palindrome pairs [Codeforces159D]

    [题解]Palindrome pairs [Codeforces159D] 传送门:\(Palindrome\) \(pairs\) \([CF159D]\) [题目描述] 给定一个长度为 \(N\) ...

  8. leetcode 132 Palindrome Pairs 2

    lc132 Palindrome Pairs 2 大致与lc131相同,这里要求的是最小分割方案 同样可以分割成子问题 dp[i][j]还是表示s(i~j)是否为palindrome res[i]则用 ...

  9. leetcode 131 Palindrome Pairs

    lc131 Palindrome Pairs 解法1: 递归 观察题目,要求,将原字符串拆成若干子串,且这些子串本身都为Palindrome 那么挑选cut的位置就很有意思,后一次cut可以建立在前一 ...

随机推荐

  1. 基于docker/虚拟机的esp32远程工作流

    原文:基于docker/虚拟机的esp32远程工作流 工作流框图 背景说明 为什么需要这套工作流--为了满足高效和灵活的开发方式 因为我经常需要在公司和家里切换不同的电脑工作,所以编译环境需要在远程主 ...

  2. PHP基础函数、自定义函数以及数组

    2.10 星期五  我们已经真正开始学习PHP 了,今天的主要内容是php基础函数.自定义函数以及数组, 内容有点碎,但是对于初学者来说比较重要,下面是对今天所讲内容的整理:  1 php的基本语法和 ...

  3. 淘宝客网站SEO及赚钱与揭密

  4. js 中常用的正则表达式

    主要有以下几种: 匹配中文字符的正则表达式: [\u4e00-\u9fa5] 评注:匹配中文还真是个头疼的事,有了这个表达式就好办了哦 获取日期正则表达式:\d{4}[年|\-|\.]\d{1,2}[ ...

  5. react面试宝典

    调用 setState 之后发生了什么? 在代码中调用setState函数之后,React 会将传入的参数对象与组件当前的状态合并,然后触发所谓的调和过程(Reconciliation).经过调和过程 ...

  6. 简单监控网站访问是否正常的shell脚本,邮件报警。网站恢复后继续运行。

    #!/bin/bash # 使用curl检查网页是否可以正常访问,如果无法访问则发邮件. SITE=crm.bjzgjh.com PROT=80 URL="http://$SITE:$PRO ...

  7. Mongoose学习(3)--设置环境变量

    比如我一套代码数据库代码分为中文站和英文站,每个表中我都有一个site_code字段来区分, 两个站点部署在不同的人服务器,这个时候我们就用系统环境变量来区分, 下面直接在mac下设置环境变量 vim ...

  8. Express中的Ejs模板传值问题

    在Ejs模板传值过程中,route下的变量值通过res.sender()中的变量参数传给views, 这时在views中若该变量在javascript代码中使用,可直接使用该变量,不必使用<% ...

  9. ArcGIS服务器的feature图层限制

    今天遇到了esri.layers.FeatureLayer发布一个宗地图层,里面有些数据未显示,导致数据显示不全,原来是服务中数据返回参数限制. ArcGIS的feature图层(在JavaScrip ...

  10. 数据结构之 线性表---单链表的操作B(先逆序+再删除重复元素)

    数据结构上机测试2-2:单链表操作B Time Limit: 1000MS Memory limit: 65536K 题目描述 按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删 ...