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. phone number is not known @w@ have no phone, and thus no phone number

    http://dev.mysql.com/doc/refman/5.7/en/problems-with-null.html B.5.4.3 Problems with NULL Values The ...

  2. 如何获取DIV的id

    $(obj).attr("id");参数可以是id也可以是其他例如name等属性

  3. Android 一键直接查看Sqlite数据库数据

    转自:http://www.cnblogs.com/trinea/archive/2012/11/16/2773656.html 本文主要介绍Android开发中如何一键直接查看sqlite数据库中的 ...

  4. svn 入门

    SVN版本:1.5 及更新版本 名词说明: WC:Working Copy 你的工作区 Versioned:受控的:受版本控制的 SVN是什么? SVN是开源的版本控制系统. 比CVS更多的特性.一个 ...

  5. 【QQ音乐Api】移花接木 打造自己的音乐电台

    最近突发奇想想做个在线音乐小网页.需求很简单,如下 搜索歌曲 或 歌手 在线播放音乐 借用qq 或者 百度的 音乐接口 需求明确那就直接动手了 我首先尝试的百度音乐,但是不能在线播放(提示forbid ...

  6. (转)常用的js设计模式

    模式是解决或者避免一些问题的方案. 在JavaScript中,会用到一些常用的编码模式.下面就列出了一些常用的JavaScript编码模式,有的模式是为了解决特定的问题,有的则是帮助我们避免一些Jav ...

  7. 低功耗蓝牙4.0BLE编程-nrf51822开发(5)-链路层

    链路层定义设备处于状态机中五种状态的一种: (1)旁路状态: 处于此状态下的设备不发送或接收数据,处于其它状态下都可以转到此状态. (2)广告状态: 处于此状态的设备发送广播包或者监听.响应广播包.可 ...

  8. nginx常用变量

    $args, 请求中的参数; $content_length, HTTP请求信息里的”Content-Length”; $content_type, 请求信息里的”Content-Type”; $do ...

  9. C#判断文件是复制还是剪切

    private void button1_Click(object sender, EventArgs e){IDataObject vDataObject = Clipboard.GetDataOb ...

  10. Mysql 只导出数据,不包含表结构

    mysqldump -u${user} -p${passwd} --no-create-info --database ${dbname} --table ${tablename} > ${ta ...