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

解题思路

首先想到的是暴力组合,分别检验所有组合是否为回文,该方法提交后超时,暴力代码如下:

//Time Limit Exceeded
public class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> indices = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < words.length; j++) {
                if (j == i) {
                    continue;
                } else {
                    String temp = words[i] + words[j];
                    if (isPalindrome(temp)) {
                        List<Integer> list = new ArrayList<>();
                        list.add(i);
                        list.add(j);
                        indices.add(list);
                    }
                }
            }
        }
        return indices;
    }

    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;
    }
}

于是想到另一种思路:

  1. 对于空字符串,如果数组中有回文字符串,则将空字符串与回文字符串进行组合。
  2. 对于非空字符串,将其进行拆分,如果其中一段为回文,并且数组中可以找到另一段的逆序字符串,则说明可以组合为回文。
    例如:”sssll” = “ss” + “sll”,而且数组中存在”lls”,因此组合”lls”和”sssll”。

注意:组合两个字符串时,需要注意顺序问题。如果字符串前半段为回文,则另一个字符串需要组合在前面;如果字符串后半段为回文,则另一个字符串需要组合在后面。

实现代码

//Runtime: 247 ms
public class Solution {
    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);
                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;
    }
}
时间: 2024-10-31 11:15:14

[LeetCode] Palindrome Pairs的相关文章

[LeetCode] Palindrome Number &amp;amp; Valid Palindrome - 回文系列问题

题目概述: Determine whether an integer is a palindrome. Do this without extra space. 题目分析: 判断数字是否是回文 例如121.656.3443 方法有很多,正着看和到着看两数相同:当然负数显然不是回文 我的方法: 第一种方法: 由于没有没有看到前面的without extra space.采用的方法是把数字转换为字符串,依次比较最前和最后两个字符是否相同,直到遍历完毕. /** * 判断一个数字是否是回文数字 Pal

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

LeetCode 9 Palindrome Number (回文数)

翻译 确定一个整数是否是回文数.不能使用额外的空间. 一些提示: 负数能不能是回文数呢?(比如,-1) 如果你想将整数转换成字符串,但要注意限制使用额外的空间. 你也可以考虑翻转一个整数. 然而,如果你已经解决了问题"翻转整数(译者注:LeetCode 第七题), 那么你应该知道翻转的整数可能会造成溢出. 你将如何处理这种情况? 这是一个解决该问题更通用的方法. 原文 Determine whether an integer is a palindrome. Do this without ex

[LeetCode]234.Palindrome Linked List

题目 Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time and O(1) space? 思路 利用双指针法找到链表中点位置,链表中点以后的的元素(不包括中点元素)翻转,再跟链表中点位置以前的元素一一匹配. 代码 /*--------------------------------------- * 日期:2015-07-18 * 作者:SJF01

[LeetCode]9.Palindrome Number

[题目] Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of usin

leetcode 9 Palindrome Number 回文数

Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using ext

[LeetCode]125.Valid Palindrome

[题目] Valid Palindrome  Total Accepted: 3479 Total Submissions: 16532My Submissions Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a pa

[LeetCode]24.Swap Nodes in Pairs

[题目] Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the lis

[LeetCode]132.Palindrome Partitioning II

题目 Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa&qu