336. Palindrome Pairs

来源:互联网 发布:网线端口坏了是怎样的 编辑:程序博客网 时间:2024/06/03 19:33

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<List<Integer>> palindromePairs(String[] words) {        Map<String, Integer> map = new HashMap<>();        for (int i = 0; i < words.length; i++) {            map.put(words[i], i);        }        List<List<Integer>> indices = new ArrayList<>();        for (int i = 0; i < words.length; i++) {            if (words[i].length() == 0) { //如果是空串,那么可以与任何回文字符串结合                for (Map.Entry<String, Integer> entry : map.entrySet()) {                    if (isPalindrome(entry.getKey())) {                        addAll(indices, i, entry.getValue());                    }                }            }            for (int j = 0; j < words[i].length(); j++) { //不是空串的话,分别切割每一个字符,查看前后是不是回文                String front = words[i].substring(0, j);//如果有回文的话,查一下剩下的在不在map里面                String back = words[i].substring(j, words[i].length());                String rfront = reverse(front);                String rback = reverse(back);                if (isPalindrome(front) && map.containsKey(rback)) {                    addAll(indices, map.get(rback), i);                }                if (isPalindrome(back) && map.containsKey(rfront)) {                    addAll(indices, i, map.get(rfront));                }            }        }        return indices;    }    private void addAll(List<List<Integer>> indices, int a, int b) {        if (a == b) {            return;        }        List<Integer> list = new ArrayList<>();        list.add(a);        list.add(b);        indices.add(list);    }    private String reverse(String word) {        return new StringBuilder(word).reverse().toString();    }    private boolean isPalindrome(String word) {        for (int i = 0, j = word.length() - 1; i < j; i++, j--) {            if (word.charAt(i) != word.charAt(j)) {                return false;            }        }        return true;    }    


原创粉丝点击