1. Description

  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"]

2. Answer  

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;
}
//build the map save the key-val pairs: String - idx
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < words.length; i++){
map.put(words[i], i);
} //special cases: "" can be combine with any palindrome string
if(map.containsKey("")) {
int blankIdx = map.get("");
for(int i = 0; i < words.length; i++) {
if(isPalindrome(words[i])) {
if(i == blankIdx)
continue;
res.add(Arrays.asList(blankIdx, i));
res.add(Arrays.asList(i, blankIdx));
}
}
} //find all string and reverse string pairs
for(int i = 0; i < words.length; i++) {
String cur_r = reverseStr(words[i]);
if(map.containsKey(cur_r)) {
int found = map.get(cur_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
} //find the pair s1, s2 that
//case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1)
//case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2)
for(int i = 0; i < words.length; i++) {
String cur = words[i];
for(int cut = 1; cut < cur.length(); cut++) {
if(isPalindrome(cur.substring(0, cut))) {
String cut_r = reverseStr(cur.substring(cut));
if(map.containsKey(cut_r)) {
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(found, i));
}
}
if(isPalindrome(cur.substring(cut))) {
String cut_r = reverseStr(cur.substring(0, cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
}
} return res;
} public String reverseStr(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
} public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j){
if(s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}

【LeetCode】Palindrome Pairs(336)的更多相关文章

  1. 【leetcode】Reverse Integer(middle)☆

    Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 总结:处理整数溢出 ...

  2. 【leetcode】Happy Number(easy)

    Write an algorithm to determine if a number is "happy". A happy number is a number defined ...

  3. 【LeetCode】Reconstruct Itinerary(332)

    1. Description Given a list of airline tickets represented by pairs of departure and arrival airport ...

  4. 【leetcode】Course Schedule(middle)☆

    There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prer ...

  5. 【leetcode】Word Break (middle)

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...

  6. 【LeetCode】Counting Bits(338)

    1. Description Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num ...

  7. 【LeetCode】Self Crossing(335)

    1. Description You are given an array x of n positive numbers. You start at point (0,0) and moves x[ ...

  8. 【leetcode】Rotate List(middle)

    Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1 ...

  9. 【leetcode】Partition List(middle)

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr ...

随机推荐

  1. Logstash之multiline 插件

    input { stdin { codec => multiline { pattern => "^\[" negate => true what => & ...

  2. 深入理解OAuth2.0协议

    1. 引言 如果你开车去酒店赴宴,你经常会苦于找不到停车位而耽误很多时间.是否有好办法可以避免这个问题呢?有的,听说有一些豪车的车主就不担心这个问题.豪车一般配备两种钥匙:主钥匙和泊车钥匙.当你到酒店 ...

  3. Your awesome titleHH

    Welcome to Jekyll! Your awesome titleHH About Blogging Like a Hacker Welcome to Jekyll! Jan 9, 2016 ...

  4. 使用 OWIN Self-Host ASP.NET Web API 2

    Open Web Interface for .NET (OWIN)在Web服务器和Web应用程序之间建立一个抽象层.OWIN将网页应用程序从网页服务器分离出来,然后将应用程序托管于OWIN的程序而离 ...

  5. 【腾讯优测干货分享】越用越卡为哪般——如何降低App的待机内存(一)

    本文来自于腾讯优测公众号(wxutest),未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/1_FKMbi1enpcKMqto-o_FQ 作者:腾讯TMQ专项测试 ...

  6. 旺信UWP正式版发布

    下载链接:https://www.microsoft.com/store/apps/9nblggh5lq9x 各位园主好,在旺信Beta版发布后近两个月,我们的新版本1.1.0终于上线了,并且更名为旺 ...

  7. Redis系列(六)-SortedSets设计技巧

    阅读目录: 介绍 Score占位 更多位信息 总结 介绍 Redis Sorted Sets是类似Redis Sets数据结构,不允许重复项的String集合.不同的是Sorted Sets中的每个成 ...

  8. MySQL MMM高可用方案

    200 ? "200px" : this.width)!important;} --> 介绍 本篇文章主要介绍搭建MMM方案以及MMM架构的原理.这里不介绍主从.主主的搭建方 ...

  9. 【VC++技术杂谈004】使用微软TTS语音引擎实现文本朗读

    本文主要介绍如何使用微软TTS语音引擎实现文本朗读,以及生成wav格式的声音文件. 1.语音引擎及语音库的安装 TTS(Text-To-Speech)是指文本语音的简称,即通过TTS引擎把文本转化为语 ...

  10. Java批处理ExecutorService/CompletionService

    服务端接收一个请求,常常需要同时进行几个计算或者向其他服务发送请求,最后拼装结果返回上游.本文就来看下JDK提供几个并行处理方案,牵涉到ExcecutorService/CompletionServi ...