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;
}
}

另有Trie做法未深究https://discuss.leetcode.com/topic/39585/o-n-k-2-java-solution-with-trie-structure-n-total-number-of-words-k-average-length-of-each-word/2

Leetcode: Palindrome Pairs的更多相关文章

  1. [LeetCode] Palindrome Pairs 回文对

    Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that t ...

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

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

  3. LeetCode 336. Palindrome Pairs

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

  4. leetcode 132 Palindrome Pairs 2

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

  5. leetcode 131 Palindrome Pairs

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

  6. LeetCode:Palindrome Partitioning,Palindrome Partitioning II

    LeetCode:Palindrome Partitioning 题目如下:(把一个字符串划分成几个回文子串,枚举所有可能的划分) Given a string s, partition s such ...

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

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

  8. LeetCode: Palindrome Partition

    LeetCode: Palindrome Partition Given a string s, partition s such that every substring of the partit ...

  9. [LeetCode] Palindrome Partitioning II 解题笔记

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

随机推荐

  1. space ship

    按下向上箭头,飞船速度不是一直增加 而且飞船移动的方向是固定的不是有角度的 按下箭头飞船可以飞了,但是不减速 加一个keyup handler就可以啦!可以一直加速,不按的时候也可以减速 按下向下按钮 ...

  2. Diode

    Diode https://zh.wikipedia.org/wiki/真空管 抽真空 电子在于其放射过程中,因会与空气中之组成分子相撞而产生阻力,因此电子经由如空气之类的介质来移动的话,将会比在真空 ...

  3. Java 遍历Map时 删除元素

    Java代码   package,,,,,,,,,,,==){ System.out.println("delete this: "+key+" = "+key ...

  4. android ListView详解继承ListActivity

    [转]http://www.cnblogs.com/allin/archive/2010/05/11/1732200.html 在android开发中ListView是比较常用的组件,它以列表的形式展 ...

  5. Ajax 填充 前端页面

  6. duplicate symbol _OBJC_CLASS 错误处理方法

    错误: ld: duplicate symbol _OBJC_CLASS_$_************ in **************** 一种可能性是你的项目的不同group里有着相同名称的类 ...

  7. php---文件上传分析

    文件上传: 先抄一段:预定义变量$_FILES数组有5个内容:       $_FILES['userfile']['name']——客户端机器文件的原名称       $_FILES['userfi ...

  8. 让Eclipse不格式化数组或某段代码

    用过eclipse ctrl+shit+f的人肯定都感觉eclipse这个功能很爽. 但对于数组,有时候就不是这样了. 比如在opengl中定义一些顶点信息: int one = 0x010000; ...

  9. 使用mysqli_stmt类

    在生成网页时,许多PHP脚本通常都会执行除参数以外,其他部分完全相同的查询语句,针对这种重复执行一个查询,每次迭代使用不同的参数情况,MySQL从4.1版本开始提供了一种名为预处理语句(prepare ...

  10. No mapping found for HTTP request with URI [] in DispatcherServlet with name 'appServlet'

    项目是使用SpringMVC (1)在浏览器中访问,后台总报错: No mapping found for HTTP request with URI [] in DispatcherServlet ...