https://leetcode.com/problems/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"]

public class Solution {

    public static boolean isPalindrome(StringBuffer sb) {

        if(sb == null || sb.length() == 0)  return true;

        int l = 0, r = sb.length()-1;

        while(l < r) {
if(sb.charAt(l) != sb.charAt(r)) return false;
++l; --r;
} return true;
} public static void buildMappings(String[] words, HashMap<String, HashSet<String> > mapping) { for(int i=0; i<words.length; ++i) { StringBuffer sb = new StringBuffer(words[i]);
HashSet<String> adj = new HashSet<String> (); for(int j=0; j<=sb.length(); ++j) {
/** partition words[i] into two parts */
StringBuffer prefix = new StringBuffer(sb.substring(0, j));
StringBuffer suffix = new StringBuffer(sb.substring(j)); /** check whether or not the prefix of words[i] is palindrome */
/** if it does, then the prefix can be the rotated point, otherwise not*/
if(isPalindrome(prefix)) {
/** adj stores the strings where suffix + words[i] is palindrome */
adj.add(suffix.reverse().toString());
} if(isPalindrome(suffix)) {
/** adj stores the strings where words[i] + prefix is palindrome */
adj.add(prefix.reverse().toString());
}
}
/** add it to mapping */
mapping.put(sb.toString(), adj); } HashSet<String> hs = new HashSet<String> ();
for(int i=0; i<words.length; ++i) { StringBuffer sb = new StringBuffer(words[i]); if(isPalindrome(sb)) {
hs.add(sb.toString());
}
} for(int i=0; i<words.length; ++i) { if(words[i].equals("")) {
HashSet<String> adj = new HashSet<String> ();
adj.addAll(hs);
mapping.put(words[i], adj);
}
} } public List<List<Integer>> palindromePairs(String[] words) { HashSet<List<Integer> > hres = new HashSet<List<Integer> > ();
List<List<Integer> > res = new ArrayList<List<Integer> > (); HashMap<String, HashSet<String> > mapping = new HashMap<String, HashSet<String> > ();
buildMappings(words, mapping); HashMap<String, Integer> dict = new HashMap<String, Integer> ();
for(int i=0; i<words.length; ++i) {
dict.put(words[i], i);
} Iterator iter = mapping.entrySet().iterator();
while(iter.hasNext()) {
HashMap.Entry entry = (HashMap.Entry) iter.next(); String str = (String) entry.getKey();
int lpos = dict.get(str);
//System.out.print(str + " ==> ");
HashSet<String> hs = (HashSet<String>) entry.getValue();
Iterator<String> itc = hs.iterator(); while(itc.hasNext()) {
String s = itc.next(); //System.out.print(s + " "); if(dict.containsKey(s)) {
int rpos = dict.get(s);
if(lpos != rpos) { StringBuffer sb1 = new StringBuffer(str).append(s);
if(isPalindrome(sb1)) {
List<Integer> ll = new ArrayList<Integer> ();
ll.add(lpos);
ll.add(rpos);
hres.add(ll);
} StringBuffer sb2 = new StringBuffer(s).append(str);
if(isPalindrome(sb2)) {
List<Integer> ll2 = new ArrayList<Integer> ();
ll2.add(rpos);
ll2.add(lpos);
hres.add(ll2);
}
}
} }//System.out.println();
} res.addAll(hres); return res;
}
}

leetcode@ [336] Palindrome Pairs (HashMap)的更多相关文章

  1. LeetCode 336. Palindrome Pairs

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

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

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

  3. 336. Palindrome Pairs(can't understand)

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

  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 Pairs(336)

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

  7. 【leetcode】336. Palindrome Pairs

    题目如下: 解题思路:对于任意一个word,要找出在wordlist中是否存在与之能组成回文的其他words,有两种思路.一是遍历wordlist:二是对word本身进行分析,找出能组成回文的word ...

  8. [Leetcode] 336. Palindrome Pairs_Hard

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

  9. 336 Palindrome Pairs 回文对

    给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文.示例 1:给定 words = ["bat&quo ...

随机推荐

  1. 用maven进行测试

    maven的重要职责之一就是自动运行单元测试,它通过maven-surefire-plugin与主流的单元测试框架junit和testng集成,并且能够自动生成丰富的结果报表. maven并不是一个单 ...

  2. maven小项目注册服务(一)--email和persist模块

    跟着书里的讲解,跟着做了一遍该项目: 首先明白注册账户的需求: 账号的lD和Email地址都可以用来唯一地标识某个用户,而显示名称则用来显示在页面下,方便浏览.注册的时候用户还需要输入两次密码,以确保 ...

  3. arcgis engine 开发之QI

    ArcGIS Engine开发基础之QI AO开发中QI(接口查询)非常重要,从某种意义上说不会QI就不会做AO开发. 在讲ArcGIS Engine开发QI实例操作之前,以一个现实生活例子以方便大家 ...

  4. Asterisk服务安装配置和启动

    Asterisk服务安装配置和启动 2014年11月4日 11:36 注意: 更新源的重要性 源的地址: http://fffo.blog.163.com/blog/static/2119130682 ...

  5. IOSTimer的例子留个备注

    1.创建一个定时器 ,以下是便利构造器方法,+ scheduledTimerWithTimeInterval:invocation:repeats:+ scheduledTimerWithTimeIn ...

  6. java.lang.NoSuchMethodError: No static method setLayoutDirection(Landroid/graphics/drawable/Drawable;I)V in class Landroid/support/v4/graphics/drawable/DrawableCompat

    Bug: java.lang.NoSuchMethodError: No static method setLayoutDirection(Landroid/graphics/drawable/Dra ...

  7. [leetcode72]Edit Distance(dp)

    题目链接:https://leetcode.com/problems/edit-distance/ 题意:求字符串的最短编辑距离,就是有三个操作,插入一个字符.删除一个字符.修改一个字符,最终让两个字 ...

  8. 1137. Bus Routes(dfs)

    1137 做过一样的 怎么又忘了 再一次搜超时 不用回溯 #include <iostream> #include<cstdio> #include<cstring> ...

  9. Android远程图片获取和本地缓存

    对于客户端——服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量,对 应用来说,如果处理不好这个问题,那会让用户很崩溃,不知不觉手机流量就用完了,等用户发现是你的应用 ...

  10. WebActivatorEx

    using System; using NLog; using System.Web.Optimization; [assembly: WebActivatorEx.PreApplicationSta ...