给定不同单词组成的数组,俩俩拼接成回文,记录顺序索引

//    5.20
//    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 List> palindromePairs(String[] words) { //Time Limit Exceeded
        List> list = new ArrayList>();
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < words.length; j++) {
                if (i != j && twoWordIntegrateIsPalindrome(words[i],words[j])) {
                    List tempList = new ArrayList(Arrays.asList(i,j));
                    list.add(tempList);
                }
            }
        }
        return list;
    }
    
    static boolean twoWordIntegrateIsPalindrome(String str1, String str2) {
        StringBuffer str = new StringBuffer(str1 + str2);
        return (str1 + str2).equals(str.reverse().toString());
    }

AC版

public List> palindromePairs1(String[] words) { //Time Limit Exceeded
        List> list = new ArrayList>();
        HashMap map = new HashMap();
        for (int i = 0; i < words.length; i++) {
            map.put(words[i], i);
        }
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j <= words[i].length(); j++) {
                String preString = words[i].substring(0,j);
                String laString = words[i].substring(j);
                if (isPalindrome(preString)) {
                    String tempString = new StringBuffer(laString).reverse().toString();
                    if (map.containsKey(tempString) && map.get(tempString) != i) {
                        List tempList = new ArrayList(Arrays.asList(map.get(tempString),i));
                        list.add(tempList);
                    }
                }
                if (isPalindrome(laString)) {
                    String tempString = new StringBuffer(preString).reverse().toString();
                    if (map.containsKey(tempString) && map.get(tempString) != i && laString.length() != 0) {
                        List tempList = new ArrayList(Arrays.asList(i,map.get(tempString)));
                        list.add(tempList);
                    }
                }
            }
        }
        return list;
    }
    
    static boolean isPalindrome(String str) {
        String str1 = new StringBuffer(str).reverse().toString();
        return str1.equals(str);
    }

你可能感兴趣的:(给定不同单词组成的数组,俩俩拼接成回文,记录顺序索引)