LeetCode 336. Palindrome Pairs(字典树)

336. Palindrome Pairs

Hard

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:

Input: [“abcd”,“dcba”,“lls”,“s”,“sssll”]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are [“dcbaabcd”,“abcddcba”,“slls”,“llssssll”]
Example 2:

Input: [“bat”,“tab”,“cat”]
Output: [[0,1],[1,0]]
Explanation: The palindromes are [“battab”,“tabbat”]

题意

给定一个字符串数组,找到数组中的两个不同的字符串,拼接之后可以成为回文字符串

思路

字符串s和字符串t拼接成回文字符串的4种情况:

  1. s是回文字符串 && t是空串 || t是回文字符串 && s是空串 => s + t, t + s都是回文字符串
  2. t是s的逆序 => s + t, t + s都是回文字符串
  3. s可以分为s1, s2 st. s1 + s2 == s && s1是回文字符串 && s2是t的逆序 => t + s是回文字符串
  4. s可以分为s1, s2 st. s1 + s2 == s && s1是t的逆序 && s2是回文字符串 => s + t是回文字符串

用字典树存储字符串数组,可以实现O(w)的字符串查找效率。算法总的时间复杂度为O(nw),其中n是字符串数组的长度,w是最长的字符串的长度。

代码

class Solution {
   
    class TrieNode {
   
        public int index = -1;
        public TrieNode[] next = new TrieNode[26];
        
        public TrieNode(int _index) {
   
            index = _index;
        }
    }
    
    private void addPair(List<List<Integer>> ans, int n1, int n2) {
   
        List<Integer> tmp = new ArrayList<Integer>();
        tmp.add(n1);
        tmp.add(n2);
        ans.add(tmp);
    }
    
    private boolean checkPalindrome(String s) {
   
        int i = 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值