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. Windows 下 Nginx + PHP + Xdebug + PHPStorm 调试环境配置

    前期条件:安装好 Nginx.PHP.PHPStorm,使得可以正常访问 一.为 PHP 安装 Xdebug 到 Xdebug 的官网(http://xdebug.org/download.php)下 ...

  2. toast 防止一直不停弹出,累积显示

    private Toast mToast = null; public void showTextToast(String msg) { if (mToast == null) { mToast = ...

  3. Java 特殊性领会

    1. 字符串比较绝对不能用 == 而必须是 xx.equals() 2. 多有对象new 后都是以引用的方式存在着 3. 数组list, map 类型都不能边用for 循环边删除,迭代器可以 eg: ...

  4. 第四章 跨平台图像显示库——SDL 第一节 与SDL第一次亲密接触

    http://blog.csdn.net/visioncat/article/details/1596576 GCC for Win32 开发环境介绍(5) 第四章 跨平台图像显示库——SDL 第一节 ...

  5. Block的简单使用

    代码块本质上是和其他变量类似.不同的是,代码块存储的数据是一个函数体.使用代码块是,你可以像调用其他标准函数一样,传入参数,并得到返回值. 代码块本质上是变量,只不过它存储的数据是一个函数体,因此名字 ...

  6. 物联网操作系统HelloX V1.80测试版发布

    经过HelloX开发团队近半年的努力,在HelloXV1.79版本基础上,增加许多功能特性,并对V1.79版本的一些特性进行了进一步优化之后,正式形成HelloX V1.80测试版本.经相对充分的测试 ...

  7. 【转】MySQL USE NAMES 'UTF8'

    先说MySQL的字符集问题.Windows下可通过修改my.ini内的 # CLIENT SECTION [mysql] default-character-set=utf8 # SERVER SEC ...

  8. ios证书

    内容提要: 安装app时提示 “无法下载应用,此时无法安装“XXX””.我遇到过多次是由于ios的app出现证书问题.本篇文章讲解用ios证书制作过程,以及每个步骤的解释. 正文: Xcode签名至少 ...

  9. Android开发笔记:打包数据库

    对于数据比较多的控制一般会加入SQLite数据库进行数据存储,在打包时这些数据库是不自动打包到apk中的,如何创建数据库呢 方法1:将创建数据库的sql语句在SQLiteHelper继承类中实现,在第 ...

  10. JQuery 方法简写

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...