力扣 472. 连接词

使用前缀树解决连接字符串问题
该博客介绍了一种利用前缀树数据结构解决判断字符串数组中长串是否能由短串组合的问题。首先对字符串数组进行排序,然后通过深度优先搜索(DFS)在前缀树中检查每个字符串是否可由已存入的字符串拼接而成。如果可以,则将其添加到结果列表中,否则将当前字符串插入前缀树。这个方法有效地避免了重复搜索和提高了效率。

题目来源:https://leetcode-cn.com/problems/concatenated-words/

大致题意:
给定一个字符串数组,判断其中的长字符串能否由短字符串连接组成,返回能被短串组成的长串

思路

这波是前缀树(字典树)的搜索,老朋友换新衣服
既然要用短串组成长串,那么就需要先把短串插入字典树中,然后遇到长串就搜索

排序 + 前缀树 + DFS
  1. 构建前缀树类
  2. 将给定字符串数组排序,然后遍历字符串数组,遇到空串直接跳过
  3. 对于当前遍历的字符串,先在前缀树中搜索它是否可以由存入的字符串组成,若可以加入答案集合,否则加入前缀树

在前缀树中搜索当前字符串能否被存入的字符串组成的方法可以概括为:

  1. 从索引 0 开始遍历字符串
  2. 若当前位置字符在前缀树中对应节点为空,直接返回 false
  3. 若当前位置不为空,且当前位置是一个字符串结尾,于是标记位置,从下一个位置开始重新在前缀树中搜索,也就是找到了拼接的字符串,再在剩余部分找下一个字符串。若仍找到,那么重复搜索,直至未找到对应串返回 false,或者字符串遍历结束返回 true
  4. 若当前位置不为空,但当前位置不是结尾,顺序遍历下一个

代码:

public class FindAllConcatenatedWordsInADict {
    Trie trie = new Trie();
    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> ans = new ArrayList<>();  
        // 排序
        Arrays.sort(words, (a, b) -> a.length() - b.length());
        for (String word : words) {
            // 跳过空串
            if (word.length() == 0) {
                continue;
            }
            // 在前缀树遍历字符串,若有加入答案集合
            if (dfs(word, 0)) {
                ans.add(word);
            } else {    // 没有则插入前缀树
                insert(word);
            }
        }
        return ans;
    }
    // 前缀树搜索
    public boolean dfs(String word, int start) {
        int n = word.length();
        // 若开始位置即为字符串长度,表示搜索完毕,word 可以由前缀树的字符串拼接组成
        if (n == start) {
            return true;
        }
        Trie node = trie;
        for (int i = start; i < n; i++) {
            int idx = word.charAt(i) - 'a';
            // 若对应子节点不存在,直接返回 false
            if (node.children[idx] == null) {
                return false;
            }
            node = node.children[idx];
            // 若子节点为前缀树中存的结尾节点
            if (node.isEnd) {
                // 那么从下一位置开始,重新在前缀树中搜索
                // 剩余部分也搜索到,返回 true
                if (dfs(word, i + 1))
                    return true;
            }
        }
        // 之前未返回 true,即代表当前串不可以由前缀树中的串拼接组成
        return false;
    }
    //  前缀树插入
    public void insert(String word) {
        Trie node = trie;
        int n = word.length();
        for (int i = 0; i < n; i++) {
            int idx = word.charAt(i) - 'a';
            if (node.children[idx] == null) {
                node.children[idx] = new Trie();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }
    // 前缀树类
    class Trie {
        Trie[] children;
        boolean isEnd;
        public Trie() {
            children = new Trie[26];
            isEnd = false;
        }
    }
}
### 解决方案概述 对于LeetCode 1584题——连接所有点的最小费用,目标是在给定平面上的一组点之间建立边,使得这些点全部连通,并且总成本最低。此问题可以通过构建最小生成树(Minimum Spanning Tree, MST)[^2]来解决。 #### Prim's Algorithm 实现方法 Prim’s算法是一种用于求解无向图中最小生成树的有效贪心算法。该算法通过逐步扩展已有的部分生成树直到覆盖所有的顶点为止,在每一步都选择当前未加入的部分中最短的边。 ```python import heapq def minCostConnectPoints(points): n = len(points) # 计算曼哈顿距离作为权重函数 def manhattan(p1, p2): return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1]) visited = set() heap = [(0, 0)] # (cost, point_index) result = 0 while len(visited) < n: cost, i = heapq.heappop(heap) if i in visited: continue visited.add(i) result += cost for j in range(n): if j not in visited and j != i: heapq.heappush(heap, (manhattan(points[i], points[j]), j)) return result ``` 上述代码实现了基于优先队列优化版本的Prim’s算法。首先定义了一个辅助函数`manhattan()`用来计算两点之间的曼哈顿距离;接着初始化一个小根堆存储候选节点及其对应的代价;最后进入循环直至访问过所有节点并累加路径长度得到最终的结果。 #### Kruskal's Algorithm 实现方式 Kruskal’s算法也是一种常用的MST算法,它按照从小到大的顺序处理各条边,只当一条边不会形成环路时才将其添加至正在形成的森林里。为了高效实现这一点,可以采用Union-Find数据结构来进行动态集合操作。 ```python class UnionFind(object): def __init__(self, size): self.parent = list(range(size)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, u, v): rootU = self.find(u) rootV = self.find(v) if rootU == rootV: return False else: self.parent[rootU] = rootV return True def minCostConnectPoints_kruskal(points): edges = [] n = len(points) for i in range(n): for j in range(i+1, n): distance = abs(points[i][0] - points[j][0]) + \ abs(points[i][1] - points[j][1]) edges.append((distance, i, j)) uf = UnionFind(n) edges.sort() res = 0 count = 0 for dist, u, v in edges: if uf.union(u, v): res += dist count += 1 if count >= n-1: break return res ``` 这段Python程序展示了如何利用Kruskal的方法解决问题。创建了名为`edges`列表保存所有可能存在的边以及它们各自的权值(即两个端点间的曼哈特尼距离),之后对其进行升序排列。随后遍历排序后的边集尝试将符合条件的新边纳入结果集中去,同时维护一个计数器确保恰好选择了\(n−1\)条独立边构成一棵完整的树形结构。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三更鬼

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值