Leetcode: 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"]
Naive Solution: Time: O(n^2*k)
with n the total number of words in the "words" array and k the average length of each word: check each combination see if it's palindrome. TLE of course.
Better Solution: Time: O(n*k^2)
think of a word A which contains two part,
1. A = XX + B, XX is palindrome, then "B_reverse + XX + B" will make a palindrome, find if B_reverse exists in the the list
2. A = C + XX , then "C + XX + C_reverse" will make a palindrome, find if C_reverse exists in the list,
To ensure quick search, use HashMap
Be careful about duplicate search: [abcd, dcba],
in first iteration, we look at word abcd, at iteration where sndHalf == "", we add {0,1}
in second iteration, we look at word dcba, at iteration where fstHaf == "", we also add {0, 1}, duplicates
public class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (words==null || words.length==0) return res;
Map<String, Integer> map = new HashMap<>();
for (int i=0; i<words.length; i++) {
map.put(words[i], i);
}
for (int i=0; i<words.length; i++) {
int len = words[i].length();
for (int j=0; j<=words[i].length(); j++) {
String fstHalf = words[i].substring(0, j);
String sndHalf = words[i].substring(j); if (isPalindrome(fstHalf)) {
String sndHalfRev = new StringBuffer(sndHalf).reverse().toString();
if (map.containsKey(sndHalfRev) && map.get(sndHalfRev)!=i) { //"aaaa" case
ArrayList<Integer> item = new ArrayList<Integer>();
item.add(map.get(sndHalfRev));
item.add(i);
res.add(new ArrayList<Integer>(item));
}
}
if (isPalindrome(sndHalf)) {
String fstHalfRev = new StringBuffer(fstHalf).reverse().toString();
if (map.containsKey(fstHalfRev) && map.get(fstHalfRev)!=i && sndHalf.length()!=0) {
ArrayList<Integer> item = new ArrayList<Integer>();
item.add(i);
item.add(map.get(fstHalfRev));
res.add(new ArrayList<Integer>(item));
}
}
}
}
return res;
} public boolean isPalindrome(String str) {
int r = str.length()-1;
int l = 0;
while (l <= r) {
if(str.charAt(l++) != str.charAt(r--)) return false;
}
return true;
}
}
Leetcode: Palindrome Pairs的更多相关文章
- [LeetCode] Palindrome Pairs 回文对
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that t ...
- 【LeetCode】336. Palindrome Pairs 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 HashTable 相似题目 参考资料 日期 题目地 ...
- LeetCode 336. Palindrome Pairs
原题链接在这里:https://leetcode.com/problems/palindrome-pairs/ 题目: Given a list of unique words, find all p ...
- leetcode 132 Palindrome Pairs 2
lc132 Palindrome Pairs 2 大致与lc131相同,这里要求的是最小分割方案 同样可以分割成子问题 dp[i][j]还是表示s(i~j)是否为palindrome res[i]则用 ...
- leetcode 131 Palindrome Pairs
lc131 Palindrome Pairs 解法1: 递归 观察题目,要求,将原字符串拆成若干子串,且这些子串本身都为Palindrome 那么挑选cut的位置就很有意思,后一次cut可以建立在前一 ...
- LeetCode:Palindrome Partitioning,Palindrome Partitioning II
LeetCode:Palindrome Partitioning 题目如下:(把一个字符串划分成几个回文子串,枚举所有可能的划分) Given a string s, partition s such ...
- DP VK Cup 2012 Qualification Round D. Palindrome pairs
题目地址:http://blog.csdn.net/shiyuankongbu/article/details/10004443 /* 题意:在i前面找回文子串,在i后面找回文子串相互配对,问有几对 ...
- LeetCode: Palindrome Partition
LeetCode: Palindrome Partition Given a string s, partition s such that every substring of the partit ...
- [LeetCode] Palindrome Partitioning II 解题笔记
Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...
随机推荐
- the basic index concept
Computer Science An Overview _J. Glenn Brookshear _11th Edition Over the years numerous variations o ...
- (转)面试题--JAVA中静态块、静态变量加载顺序详解
public class Test { //1.第一步,准备加载类 public static void main(String[] args) { new Test(); //4.第四步,new一个 ...
- DefaultHttpClient使用
转自:http://username2.iteye.com/blog/1664995 博客分类: java 工具类 javaio ]; } json = JSONObject.fromObject ...
- Super不要在Super构造器中调用覆盖方法
import java.util.Date; public class Super{ public Super(){ System."); overrideMe(); System.&quo ...
- Python 虚拟环境Virtualenv
本人也是Python爱好者,众所周知,Python扩展多,每次为了测试,安装各种各样的扩展,这样导致本地的Python环境非常混乱,就有人想到搞个隔离环境 和 本地环境没有关系,随时可以删除这个隔离 ...
- Bootstrap 下拉菜单和滚动监听插件
一.下拉菜单 常规使用中,和组件方法一样,代码如下: //声明式用法 <div class="dropdown"> <button class="btn ...
- Architecture of a Highly Scalable NIO-Based Server
一. thread-per-connection The thread-per-connection approach uses an exclusive worker thread for each ...
- Java 实现导出excel表 POI
1.首先下载poi-3.6-20091214.jar 2.Student.java import java.util.Date; public class Student { private int ...
- django internal search
最近改进了项目中的站内搜索的功能,增加了全文索引,提升了搜索速度.因为项目框架是django,所以采用django+haystack+pyelasticsearch+elasticsearch的方式实 ...
- centos 6.4 安装视频解码器
cd /etc/yum.repos.d/ wget http://mirrors.163.com/.help/CentOS6-Base-163.repo yum update rpm -Uhv htt ...