[LeetCode] Palindrome Pairs

来源:互联网 发布:山东双轨直销软件 编辑:程序博客网 时间:2024/06/04 23:23

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 {//这里的去重一定要注意 重点在于对一个字符串整体反转找对应的串的时候,这时候只找一边即可,如果找两边,会造成重复,重点看两个for循环下标   public List<List<Integer>> palindromePairs(String[] words) {        List<List<Integer>> re=new ArrayList<List<Integer>>();        if(words.length==0) return re;        HashMap<String,Integer> map=new HashMap<String,Integer>();         for(int i=0;i<words.length;i++) map.put(words[i],i);        for(int i=0;i<words.length;i++){        String str=words[i];        for(int k=0;k<=str.length();k++){        String s1=str.substring(0,k);        String s11=str.substring(k);        String s2=reverse(s1);        if(map.containsKey(s2)&&map.get(s2)!=i&&isPar(s11)){        List<Integer> one=new ArrayList<Integer>();        one.add(i);one.add(map.get(s2));        re.add(one);        }        }        for(int k=1;k<=str.length();k++){        String s1=str.substring(k);        String s11=str.substring(0,k);        String s2=reverse(s1);        if(map.containsKey(s2)&&isPar(s11)){        List<Integer> one=new ArrayList<Integer>();        one.add(map.get(s2));one.add(i);        re.add(one);        }        }        }    return re;    }    public String reverse(String str){    StringBuffer sb=new StringBuffer();    for(int i=0;i<str.length();i++){    sb.append(str.charAt(str.length()-1-i));    }    return sb.toString();    }       public boolean isPar(String str){    for(int i=0;i<str.length()/2;i++){    if(str.charAt(i)!=str.charAt(str.length()-1-i))    return false;    }    return true;    }}