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. Aliasing 走样

    Computer Science An Overview _J. Glenn Brookshear _11th Edition Have you ever noticed the weird &quo ...

  2. 九 spring和mybatis整合

    1       spring和mybatis整合 1.1     整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用Sq ...

  3. ubuntu挂载其他分区到/home下,将当前分区内容替换

    有时候,我们装系统时,可能因为没注意,把某一个分区分小了,导致到最后,我们的那个盘容不下了, 这时,面临的两个选择就是:要么卸载一些软件,要么重新分区,重装系统,其实,还可以这样,去把其他 多余的盘分 ...

  4. Medusa: Gauges for JavaFX

    Medusa: Gauges for JavaFX https://community.oracle.com/docs/DOC-992746

  5. js 定时跳转, 格式化字符串时间

    效果 1.js中将一字符串表示的系统时间转换为Date时间对象 //js中将一串字符串转换为date类型,主要是先过滤字符,然后分割开 function parseToDate(strTime) { ...

  6. The Best Path---hdu5883(欧拉路径)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5883 题意:n 个点 m 条无向边的图,找一个欧拉通路/回路使得这个路径所有结点的异或值最大. 先判断 ...

  7. JS判断浏览器是否安装flash插件

    1.直接判断是否有flash插件 var myFlash = (function(){ if(typeof window.ActiveXObject != "undefined") ...

  8. 如何解决.NET Framework4.0的System.EnterpriseServices could not found 的问题

    我今天建基于.NET Framework4.0的webSite时报错 “System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, Pub ...

  9. .net变量判断

    <div class="AccountLevel" style="margin-top: 15px;">                <sp ...

  10. php回调函数

    1.array_filter($arr, "odd") <?php $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9); function odd ...