LeetCode 336. Palindrome Pairs(回文对)

Unity UI适配实战:从Canvas Scaler到主流游戏适配方案解析 本文深入解析Unity UI适配的核心技术,重点介绍Canvas Scaler组件的关键参数如Reference Resolution和Screen Match Mode,并提供主流游戏适配方案实战分析。通过九宫格拉伸、动态调整等技巧,帮助开发者解决多设备适配难题,提升游戏UI在不同分辨率下的表现。 阅读详情

原题网址:https://leetcode.com/problems/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"]

方法:通过Trie来发现对称的单词。

public class Solution {
    private boolean palindrome(char[] word, int i, int j) {
        while (i<j) if (word[i++] != word[j--]) return false;
        return true;
    }
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> pairs = new ArrayList<>();
        if (words == null || words.length == 0) return pairs;
        char[][] was = new char[words.length][];
        TrieNode root = new TrieNode();
        for(int i=0; i<words.length; i++) {
            was[i] = words[i].toCharArray();
            TrieNode node = root;
            for(int j=0; j<was[i].length; j++) node = node.next(was[i][j]);
            node.id = i;
        }
        if (root.id != -1) {
            for(int i=0; i<was.length; i++) {
                if (i != root.id && palindrome(was[i], 0, was[i].length-1)) {
                    Integer[] pair = new Integer[2];
                    pair[0] = root.id;
                    pair[1] = i;
                    pairs.add(Arrays.asList(pair));
                    pair = new Integer[2];
                    pair[0] = i;
                    pair[1] = root.id;
                    pairs.add(Arrays.asList(pair));
                }
            }
        }
        for(int i=0; i<was.length; i++) {
            if (was[i].length == 0) continue;
            TrieNode node = root;
            
            for(int j=was[i].length-1; j>=0; j--) {
                node = node.nexts[was[i][j]-'a'];
                if (node == null) break;
                // System.out.printf("i=%d, j=%d, words[%d]=%s, node.id=%d, palindrome=%b\n", i, j, i, words[i], node.id, palindrome(was[i], 0, j-1));
                if (node.id == -1 || node.id == i || !palindrome(was[i], 0, j-1)) continue;
                Integer[] pair = new Integer[2];
                pair[0] = node.id;
                pair[1] = i;
                pairs.add(Arrays.asList(pair));
            }
            if (node != null) {
                LinkedList<TrieNode> queue = new LinkedList<>();
                queue.add(node);
                while (!queue.isEmpty()) {
                    TrieNode trie = queue.remove();
                    if (trie.id != -1 && trie.id != i && was[trie.id].length != 0 && was[trie.id].length != was[i].length
                    && palindrome(was[trie.id], was[i].length, was[trie.id].length-1)) {
                        Integer[] pair = new Integer[2];
                        pair[0] = trie.id;
                        pair[1] = i;
                        pairs.add(Arrays.asList(pair));
                    }
                    for(int j=0; j<trie.size; j++) queue.add(trie.nexts[trie.trans[j]]);
                }
            }
        }
        return pairs;
    }
}
class TrieNode {
    int id = -1;
    TrieNode[] nexts = new TrieNode[26];
    char[] trans = new char[26];
    int size = 0;
    TrieNode next(char ch) {
        char id = (char)(ch-'a');
        if (nexts[id] == null) {
            trans[size++] = id;
            nexts[id] = new TrieNode();
        }
        return nexts[id];
    }
}


另一个实现方式:

public class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        Trie root = new Trie();
        char[][] was = new char[words.length][];
        for(int i=0; i<words.length; i++) {
            was[i] = words[i].toCharArray();
            Trie node = root;
            for(int j=0; j<was[i].length; j++) node = node.append(was[i][j]);
            node.w = i;
        }
        List<List<Integer>> results = new ArrayList<>();
        if (root.w != -1) {
            for(int i=0; i<was.length; i++) {
                if (i==root.w) continue;
                int left = 0, right = was[i].length-1;
                for(; left < right && was[i][left] == was[i][right]; left ++, right --);
                if (left >= right) {
                    Integer[] pair = new Integer[2];
                    pair[0] = root.w;
                    pair[1] = i;
                    // System.out.printf("1 root.w=%d, i=%d, pair=[%d, %d]\n", root.w, i, pair[0], pair[1]);
                    results.add(Arrays.asList(pair));
                    pair = new Integer[2];
                    pair[0] = i;
                    pair[1] = root.w;
                    // System.out.printf("2 root.w=%d, i=%d, pair=[%d, %d]\n", root.w, i, pair[0], pair[1]);
                    results.add(Arrays.asList(pair));
                }
            }
        }
        for(int i=0; i<was.length; i++) {
            Trie node = root;
            for(int j=was[i].length-1; j>=0; j--) {
                node = node.nexts[was[i][j]-'a'];
                if (node == null) break;
                if (node.w != -1 && node.w != i) {
                    int left = 0, right = was[i].length-was[node.w].length-1;
                    for(; left < right && was[i][left] == was[i][right]; left ++, right --);
                    if (left >= right) {
                        Integer[] pair = new Integer[2];
                        pair[0] = node.w;
                        pair[1] = i;
                        // System.out.printf("3 node.w=%d, i=%d, pair=[%d, %d]\n", node.w, i, pair[0], pair[1]);
                        results.add(Arrays.asList(pair));
                    }
                }
            }
            if (node != root && node != null) {
                LinkedList<Trie> queue = new LinkedList<>();
                for(int j=0; j<node.size; j++) queue.add(node.nexts[node.letters[j]-'a']);
                while (!queue.isEmpty()) {
                    Trie q = queue.remove();
                    if (q.w != -1 && q.w != i) {
                        int left = was[i].length, right = was[q.w].length-1;
                        for(; left < right && was[q.w][left] == was[q.w][right]; left ++, right --);
                        if (left >= right) {
                            Integer[] pair = new Integer[2];
                            pair[0] = q.w;
                            pair[1] = i;
                            // System.out.printf("4 q.w=%d, i=%d, pair=[%d, %d]\n", q.w, i, pair[0], pair[1]);
                            results.add(Arrays.asList(pair));
                        }
                    }
                    for(int j=0; j<q.size; j++) queue.add(q.nexts[q.letters[j]-'a']);
                }
            }
        }
        return results;
    }
}
class Trie {
    int w = -1;
    char[] letters = new char[26];
    int size;
    Trie[] nexts = new Trie[26];
    Trie append(char ch) {
        if (nexts[ch-'a'] != null) return nexts[ch-'a'];
        letters[size++] = ch;
        nexts[ch-'a'] = new Trie();
        return nexts[ch-'a'];
    }
}

如果不想使用广度优先,则可以建立前缀树和后缀树,分别检查。

public class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> results = new ArrayList<>();
        Trie forward = new Trie();
        Trie reverse = new Trie();
        char[][] was = new char[words.length][];
        
        for(int i = 0; i < words.length; i++) {
            was[i] = words[i].toCharArray();
            Trie f = forward;
            for(int j = 0; j < was[i].length; j++) {
                f = f.append(was[i][j]);
            }
            f.id = i;
            Trie r = reverse;
            for(int j = was[i].length - 1; j >= 0; j--) {
                r = r.append(was[i][j]);
            }
            r.id = i;
        }
        
        for(int i = 0; i < words.length; i++) {
            Trie f = forward;
            int j = was[i].length - 1;
            for(; j >= 0 && f != null; j--) {
                if (f.id != -1 && f.id != i) {
                    int left = 0, right = j;
                    for(; left < right && was[i][left] == was[i][right]; left++, right--);
                    if (left >= right) {
                        Integer[] result = new Integer[2];
                        result[0] = f.id;
                        result[1] = i;
                        results.add(Arrays.asList(result));
                    }
                }
                f = f.nexts[was[i][j] - 'a'];
            }
            if (j < 0 && f != null && f.id != -1 && f.id < i) {
                Integer[] result = new Integer[2];
                result[0] = f.id;
                result[1] = i;
                results.add(Arrays.asList(result));
                result = new Integer[2];
                result[0] = i;
                result[1] = f.id;
                results.add(Arrays.asList(result));
            }                
            
            Trie r = reverse;
            j = 0;
            for(; j < was[i].length && r != null; j++) {
                if (r.id != -1 && r.id != i) {
                    int left = j, right = was[i].length - 1;
                    for(; left < right && was[i][left] == was[i][right]; left++, right--);
                    if (left >= right) {
                        Integer[] result = new Integer[2];
                        result[0] = i;
                        result[1] = r.id;
                        results.add(Arrays.asList(result));
                    }
                }
                r = r.nexts[was[i][j] - 'a'];
            }
            // 引起重复
            // if (j == was[i].length && r != null && r.id != -1 && i != r.id) {
            //     Integer[] result = new Integer[2];
            //     result[0] = i;
            //     result[1] = r.id;
            //     results.add(Arrays.asList(result));
            // }
        }
        return results;
    }
}

class Trie {
    int id = -1;
    Trie[] nexts = new Trie[26];
    Trie append(char ch) {
        if (nexts[ch - 'a'] == null) nexts[ch - 'a'] = new Trie();
        return nexts[ch - 'a'];
    }
}

注意当两个字符串长度相等、字符顺序相反的时候,如何去除重复。

另一种方法是不使用Trie,而是按照长度穷举切分方法,参考:https://leetcode.com/discuss/93603/150-ms-45-lines-java-solution

【AI编程】Vibe Coding 开发环境搭建与项目实战操作详解 Vibe Coding 开发环境搭建与项目实战操作详解 阅读详情

相关推荐

Cox构建预测模型(5):如何用R语言绘制校准曲线(附全套代码)

这篇文献通过绘制两个模型的DCA曲线来评估模型的临床决策实际需求,一个是列线图模型,包括纳入列线图的全部变量,一个是TNM模型,只纳入TNM分期3个变量。A图是训练集1年、3年、5年患者的总生存期的DCA曲线;B图是训练集1年、3年、5年患者的总生存期的DCA曲线,红色线条代表列线图模型(包括构建模型的10个变量),黄色线条代表TNM模型(仅纳入TNM分期3个变量),两个模型对比,在绘制校准图之前,必须要完成数据的导入、拆分数据集的工作、预测因子的筛选,校准图的绘制是分别在训练集与验证集独立进行的。

qq_37610365的博客 1361

09 -- 回文对

回文对

JH_Cao的博客 539

什么是 WhatsApp云控 WhatsApp群发,WhatsApp协议,他们有什么区别?

下面我们sensws讲解下什么是WhatsApp云控 WhatsApp群发,WhatsApp协议

sendws的博客 3888

Leetcode 336 回文对

本文借鉴了https://discuss.leetcode.com/topic/51771/clean-c-implementation原题回放给定一个无重复字符串列表words,找出所有的序偶对(i,j),如果words[i]+words[j]是一个回文串的话。 例如: words = [“bat”, “tab”, “cat”] 返回 [[0,1], [1,0]] 回文串即[“ba

Benjamin1083的专栏 945

【2023版】基于JT808/JT1078协议的车载视频监控平台开发实战-开源架构解析

本文详细解析了基于JT808/JT1078协议的车载视频监控平台开发实战,涵盖协议核心作用、开源架构设计、开发避坑指南及二次开发建议。重点介绍了JT1078协议在音视频传输中的优化方案,以及海量位置数据存储、高可用架构等关键技术点,为开发者提供全面的实战参考。

weixin_26965807的博客 245

ROS-Industrial :simple_message

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录1. 概述2. 协议(Protocol)3. HEADER解析3.1 MSG_TYPE3.2 COMM_TYPE3.3 REPLY CODE 1. 概述 Simple_Message是ROS-Industrial的一部分,定义了用于与工业机器人控制器通信的简单消息连接协议。另外还包括处理连接受限系统的处理器和管理器类。 2. 协议(Protocol) 简单消息(simplemessage)协议定义了ROS的驱动层和机器人控制器之.

flsxyw的博客 787

[C++] LeetCode 336. 回文对

题目 给定一组独特的单词, 找出在给定列表中不同 的索引对(i, j),使得关联的两个单词,例如:words[i] + words[j]形成回文。 示例 1: 给定words = ["bat", "tab", "cat"] 返回 [[0, 1], [1, 0]] 回文是["battab", "tabbat"] 示例 2: 给定 words = ["abcd", "d

沧海漂游的博客 1154

Unity 数字孪生笔记1 工具介绍

前言 工欲善其事必先利其器 流程思考 数字孪生本质上一种基于实际物理数据的可视化方案,通过对接实际数据,在三维界面中展示孪生结果。 那么这个流程就很简单了。 整个流程分为三块:数据来源-》数据分析-》数据展示 输入数据 首先我们需要考虑我们能拿到什么。第一,实际物体的三维数据从哪里来,第二,实际数据怎么获取到。 模型数据 工业上常常会用到CAD模型,CAD模型具有精确、统一的特点,但是CAD不是三角面片,我们不能直接导出到Unity中,而且导入之后有很多不合理的地方,例如面片杂乱、面数过高等问题。针对这个

Thissky的专栏 1万+

[前缀树]leetcode336:回文对(hard)

题目: 题解: 第一步:将<单词,下标>存放在hashmap中(使用hashmap代替前缀树),将单词的长度存放在set中。 第二步:遍历单词数组,将遍历的到的单词先进行反转: 1)第一种情况:单词数组中存在两个长度相等且互为回文的单词。比如:abcd和dcba,当我们遍历到abcd时,将其反转为dcba,然后我们判断dcba是否在map中,并且dcba的下标要和abcd的下标...

algsup 796

BACnet/IP BBMD跨网段通信深度解析与最佳实践

本文介绍了在BACnet/IP网络中通过BBMD实现跨子网设备通信的关键配置方法。重点阐述了广播分发表(BDT)中掩码设置的重要性:使用子网掩码(255.255.255.0)会导致路由器拦截广播消息,而必须采用主机掩码(255.255.255.255)才能启用单播隧道机制,使BACnet广播消息封装为可路由的单播UDP包。文章详细说明了BDT条目的正确配置格式、BIP广播地址的作用,并提供了验证步骤,强调在跨网段场景中,正确设置掩码是确保设备发现和通信成功的关键因素。

零一架构师的专栏 1543

CentOS 7 Linux yum 安装 Docker,解决 Docker 镜像拉取失败问题

本文详细介绍了在 CentOS 7 系统上通过 yum 安装 Docker 的完整流程,包括卸载旧版本、配置阿里云国内镜像源、安装 Docker 及其组件、设置日志限制等关键步骤。针对国内用户常见的 Docker 镜像拉取失败问题,提供了两种实用解决方案:配置镜像加速器或通过代理访问官方源,并附带验证方法与排错指南,帮助读者高效完成 Docker 环境部署。

寒水馨 · 轻量级技术文档 · hanshuixin.org 1726

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

u010005161的博客 1430

111. 如何创建 SAP ABAP 锁对象(Lock Object)和加锁以及解锁函数

至此,我们完成了 ABAP 系统锁机制和加锁解锁函数的介绍。有了这些基础知识,大家就能在实际工作中,使用 Lock Object 和加锁解锁函数,编写出支持并发访问控制的 ABAP 应用程序了。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1553

leetcode : 336. Palindrome Pairs : 拼接回文的个数

336. Palindrome Pairs My Submissions Question Total Accepted: 1666 Total Submissions: 9046 Difficulty: Hard Given a list of unique words. Find all pairs of distinct indices (i, j

smileyk的专栏 1279

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

LeetCode 336 Palindrome Pairs(回文串)

题意:给出一个有n个单词的字典,问有多少不同的两个单词的组合使得新组合成的单词是回文串。 思路:对于每个单词,从左到右遍历一遍,对于任意一个位置,如果它的左边是回文串且右边的逆序在字典中出现,那么就存在这么一种组合,同理,如果它的右边是回文串且左边的逆序在字典中出现,那么也存在这么一种组合。 class Solution { public: vector> palindromePair

GODSPEED 2241

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

[Swift]LeetCode336. 回文对 | Palindrome Pairs

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/streng...

weixin_30268071的博客 171

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【LeetCode】336. Palindrome Pairs 回文对(Hard)(JAVA)

【LeetCode】336. Palindrome Pairs 回文对(Hard)(JAVA) 题目地址: https://leetcode.com/problems/palindrome-pairs/ 题目描述: Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words

qq_16927853的博客 205

LeetCode(336):回文对 Palindrome Pairs(Java)

2019.11.22 LeetCode 从零单刷个人笔记整理(持续更新) github:https://github.com/ChopinXBP/LeetCode-Babel 这道题本质上是要切分字符串,使得字典中的两个单词 word1[0,end] + word2[0,j-1] + word2[j,end] 或者 word1[0,j-1] + word1[j,end] + word2[0,en...

NJU_ChopinXBP的博客 365

LeetCode.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: ...

侠客小虎的博客 799

【To Understand!回文串8 哈希表】LeetCode 336. Palindrome Pairs

LeetCode 336. Palindrome Pairs Solution1:我的答案 最笨的方法,果然因为时间复杂度太高而无法AC…… 难怪是hard 只是记录一下…… class Solution { public: vector&amp;lt;vector&amp;lt;int&amp;gt;&amp;gt; palindromePairs(vector&amp;lt;string&amp;gt;&amp;amp; word

Allenlzcoder的博客 302

Leetcode 336. Palindrome Pairs 给出一种遍历字符串回文子串中心的方法

题意 给你n个不同的字符串,让你找出所有的字符串对(i, j),使得s(i) + s(j)是回文串且i不等于j 思路 这题没有给数据范围,所以你其实不知道应该给什么复杂度的算法,我看了眼Discussion,先确定了下需要的复杂度 复杂度是O(n * k ^ 2),其中k是字符串的平均长度 算法思路并不复杂,考虑第i个字符串,如果s = s(i) + s(j)是答案之一,且i是较长的字符串,那么s的

luke2834的专栏 481

leetcode 336. Palindrome Pairs 回文数字符串对 + Map加速暴力查询

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 word

JackZhangNJU的专栏 338

LeetCode //C - 336. Palindrome Pairs

【代码】LeetCode //C - 336. Palindrome Pairs。

Made in Code 2674

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 palindro...

da_kao_la的博客 283

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: Give

多看多听多总结 1718

leetcode 336 Palindrome Pairs

lc 336 Palindrome Pairs 最简单的就是每两个都拼接一下,然后判断是否为回文串 时间复杂度为o(n^2*k) n:words个数 k:word平均长度 但是我们仔细观察一下,两个word拼接之后,是如何判断是否为回文串的呢?首尾指针,匹配,向中间收缩。 假如现在有一个单词"asad",有可能和它组成回文串的字母一定结尾是a,"???????a",倒数第二个字母...

weixin_30248399的博客 171
上一篇: LeetCode 335. Self Crossing(贪吃蛇)
下一篇: LeetCode 337. House Robber III(小偷游戏)
jmspan
博客等级 码龄11年 99粉丝 431原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值