当前位置: 首页 > article >正文

Java | Leetcode Java题解之第472题连接词

题目:

题解:

class Solution {
    Trie trie = new Trie();

    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> ans = new ArrayList<String>();
        Arrays.sort(words, (a, b) -> a.length() - b.length());
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (word.length() == 0) {
                continue;
            }
            boolean[] visited = new boolean[word.length()];
            if (dfs(word, 0, visited)) {
                ans.add(word);
            } else {
                insert(word);
            }
        }
        return ans;
    }

    public boolean dfs(String word, int start, boolean[] visited) {
        if (word.length() == start) {
            return true;
        }
        if (visited[start]) {
            return false;
        }
        visited[start] = true;
        Trie node = trie;
        for (int i = start; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            node = node.children[index];
            if (node == null) {
                return false;
            }
            if (node.isEnd) {
                if (dfs(word, i + 1, visited)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public void insert(String word) {
        Trie node = trie;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
}

class Trie {
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
}

http://www.kler.cn/news/342255.html

相关文章:

  • 基于 Prometheus+Grafana+Alertmanager 搭建 K8S 云监控告警平台(附配置告警至QQ、钉钉)
  • 【JAVA开源】基于Vue和SpringBoot的卫生健康系统
  • React modal暴露ref简洁使用
  • 【uniapp小程序】使用cheerio去除字符串中的HTML标签并获取纯文本内容
  • 性能优化-SQL查询优化技巧全解
  • 服装生产管理的数字化转型:SpringBoot框架
  • Serilog文档翻译系列(八) - 记录器的生命周期、可靠性
  • Android -- [SelfView] 自定义多色渐变背景板
  • C/C++语言三大结构练习题(持续更新。。。)
  • 什么是矩阵系统,怎么选择矩阵系统,怎么oem贴牌,怎么源码搭建
  • Oracle RAC IPC Send timeout detected问题分析处理
  • 免费气象可视化的前端框架概述
  • 每日一面 day03
  • 论文翻译 | Fairness-guided Few-shot Prompting for LargeLanguage Models
  • 每天一个数据分析题(四百九十八)- Apriori算法
  • 毕业设计选题:基于php+vue+uniapp的新闻资讯小程序
  • CocosCreator基于jenkins自动构建
  • MQTT vs HTTP:谁更适合物联网?
  • [软件工程]—TFTP协议简要解析
  • wasm在云原生领域的运用