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

Solution:

思路:
Pairs like "abcd" and "dcba". Obviously, these two strings can make a palindrome pair. Suppose we are applying the solution to this case and String s1 = "abcd". When visiting the string and cut the string to substring "abcd" and "", we can know that if we reverse s1 and find the reversed string "dcba" existed thus we find the pair.
This is one of the general cases that are easily to be considered.

Pairs like "abade" and "ed". In this case, the two strings cannot be simply reversed, concatenated and made to palindrome pair as a whole. However, it is still obvious that "ed"+"abade" = "edabade" is palindromic. In this case, we need to find prefix of string1 which is palindromic and reverse the rest to make palindrom pair. This is a more general case since in the first case I introduce, actually the prefix is "".

Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> ret = new ArrayList<>(); 
        if (words == null || words.length < 2) return ret;
        Map<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++) {
            // System.out.println(words[i]);
            for (int j=0; j<=words[i].length(); j++) { // notice it should be "j <= words[i].length()"
                String str1 = words[i].substring(0, j);
                String str2 = words[i].substring(j);
                if (isPalindrome(str1)) {
                    String str2rvs = new StringBuilder(str2).reverse().toString();
                    if (map.containsKey(str2rvs) && map.get(str2rvs) != i) {
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(map.get(str2rvs));
                        list.add(i);
                        ret.add(list);
                        // System.out.printf("isPal(str1): %s\n", list.toString());
                    }
                }
                if (isPalindrome(str2)) {
                    String str1rvs = new StringBuilder(str1).reverse().toString();
                    // check "str.length() != 0" to avoid duplicates
                    if (map.containsKey(str1rvs) && map.get(str1rvs) != i && str2.length()!=0) { 
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(i);
                        list.add(map.get(str1rvs));
                        ret.add(list);
                        // System.out.printf("isPal(str2): %s\n", list.toString());
                    }
                }
            }
        }
        return ret;
    }

    private boolean isPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;
        while (left <= right) {
            if (str.charAt(left++) !=  str.charAt(right--)) return false;
        }
        return true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 子时戏闹丑时欢, 如雷大哭踢被酣, 忽又侧卧梦呢喃。 未期金榜中状元, 不盼戎装守边关, 惟愿康健又平安。
    海曲三少阅读 445评论 4 6
  • 有一种人,起早贪黑,辛苦勤劳,只为物质上得到满足;有一种人,艰苦奋斗,敏而好学,只为成绩单的分数得到提高;有一种人...
    小颖885阅读 951评论 0 1
  • 她说,如果有一天,她离开了,我该怎么办。 我说,那我会把你找回来。 她说,找不回怎么办。 那就算了,这是我的回答。...
    LeeYH阅读 410评论 0 1
  • “特斯拉”成为这个时代对未来汽车憧憬的符号,无论是传统汽车制造企业,还是怀揣“造车梦”的互联网企业都将“特斯拉”作...
    科技棱镜社阅读 299评论 0 0