leetcode@ [336] Palindrome Pairs (HashMap)
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)的更多相关文章
- LeetCode 336. Palindrome Pairs
原题链接在这里:https://leetcode.com/problems/palindrome-pairs/ 题目: Given a list of unique words, find all p ...
- 【LeetCode】336. Palindrome Pairs 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 HashTable 相似题目 参考资料 日期 题目地 ...
- 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 ...
- leetcode 132 Palindrome Pairs 2
lc132 Palindrome Pairs 2 大致与lc131相同,这里要求的是最小分割方案 同样可以分割成子问题 dp[i][j]还是表示s(i~j)是否为palindrome res[i]则用 ...
- leetcode 131 Palindrome Pairs
lc131 Palindrome Pairs 解法1: 递归 观察题目,要求,将原字符串拆成若干子串,且这些子串本身都为Palindrome 那么挑选cut的位置就很有意思,后一次cut可以建立在前一 ...
- 【LeetCode】Palindrome Pairs(336)
1. Description Given a list of unique words. Find all pairs of distinct indices (i, j) in the given ...
- 【leetcode】336. Palindrome Pairs
题目如下: 解题思路:对于任意一个word,要找出在wordlist中是否存在与之能组成回文的其他words,有两种思路.一是遍历wordlist:二是对word本身进行分析,找出能组成回文的word ...
- [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 ...
- 336 Palindrome Pairs 回文对
给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文.示例 1:给定 words = ["bat&quo ...
随机推荐
- OSCache 缓存技术
前言:OSCache标记库由OpenSymphony设计,它是一种开创性的JSP定制标记应用,提供了在现有JSP页面之内实现快速内存缓冲的功能.OSCache是个一个广泛采用的高性能的J2EE缓存框架 ...
- Collection_Other
package com.bjsxt.others.que; import java.util.ArrayDeque; import java.util.Queue; /** * 使用队列模拟银行存款业 ...
- Android Studio:libpng warning: iCCP: Not recognizing known sRGB profile that has been edited解决办法
把以前的eclipse的项目导入Android Studio中,Build项目的时候,出现了一堆错误. 如下: AAPT err(Facade for 1944774242): ERROR: 9-pa ...
- 【转载】Java中如何写一段内存泄露的程序 & ThreadLocal 介绍和使用
可以参考这段文章: link A1:通过以下步骤可以很容易产生内存泄露(程序代码不能访问到某些对象,但是它们仍然保存在内存中): 上文中提到了使用ThreadLocal造成了内存泄露,但是写的不清不楚 ...
- POJ 2752 (KMP 所有可能长度的前缀后缀) Seek the Name, Seek the Fame
题意: 求一个字符串的相同前缀后缀的所有可能的长度,这里该字符串其本身也算自己的前缀和后缀. 分析: 我们知道next数组的性质是,该字符之前的字符串的最大相同前缀后缀. 既然知道了最大的,即next ...
- Jquery 模板插件 jquery.tmpl.js 的使用方法(2):嵌套each循环,temp调用(使用预编译的模板缓存)
直接上代码吧 一:主窗口 /*#region SendChooseTargetTemplate 发送候选人主窗口模板*/ var SendChooseTargetTemplate = ''; Send ...
- mysql 分页存储过程 一次返回两个记录集(行的条数,以及行记录),DataReader的Read方法和NextResult方法
DELIMITER $$ USE `netschool`$$ DROP PROCEDURE IF EXISTS `fn_jk_GetCourses`$$ CREATE DEFINER=`root`@` ...
- 流媒体相关知识介绍 及其 RTP 应用
一.流媒体简介 随着Internet的日益普及,在网络上传输的数据已经不再局限于文字和图形,而是逐渐向声音和视频等多媒体格式过渡.目前在网络上传输音频/视频(Audio/Video,简称A/V)等多媒 ...
- 【转】定时器、sigevent结构体详解
原文网址:http://blog.163.com/zheng_he_xiang/blog/static/18650532620116311020390/ 最强大的定时器接口来自POSIX时钟系列,其创 ...
- mysql 基础命令入门学习
登陆到mysql mysql -u 用户名 -p [数据库] 显示数据库 show databases; 使用一个数据库 use 数据库名; 显示表 show tables; 纠正数据 ...