3 Star 61 Fork 5

programmercarl / kamacoder-solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
0060.匹配前缀的词典.md 2.09 KB
一键复制 编辑 原始数据 按行查看 历史
charon_cc 提交于 2024-01-12 16:33 . 卡码网第一次蓝桥杯框架

60. 匹配前缀的词典

题目链接

C

C++

Java

import java.util.Scanner;

// 字典树的节点
class TrieNode {
    boolean isWord;
    final TrieNode[] children;
    public TrieNode() {
        isWord = false;
        children = new TrieNode[26];
    }
}

// 字典树
class Trie {
    TrieNode root;

    Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            int c = word.charAt(i) - 'a';
            if (current.children[c] == null) {
                current.children[c] = new TrieNode();
            }
            current = current.children[c];
        }
        current.isWord = true;
    }

//    完整的字段树应该包含搜索功能,但是此处用不到
//    public boolean search(String word) {
//        TrieNode current = root;
//        for (int i = 0; i < word.length(); i++) {
//            int c = word.charAt(i) - 'a';
//            if (current.children[c] == null) {
//                return false;
//            }
//            current = current.children[c];
//        }
//        return current.isWord;
//    }

    public boolean startWith(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            int c = word.charAt(i) - 'a';
            if (current.children[c] == null) {
                return false;
            }
            current = current.children[c];
        }
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();

        scanner.nextLine(); // 消耗掉换行符
        Trie trie = new Trie();
        for (int i = 0; i < m; i++) {
            trie.insert(scanner.nextLine());
        }

        for (int i = 0; i < n; i++) {
            boolean isStart = trie.startWith(scanner.nextLine());
            System.out.println(isStart);
        }
    }
}

Python

JS

Go

1
https://gitee.com/programmercarl/kamacoder-solutions.git
git@gitee.com:programmercarl/kamacoder-solutions.git
programmercarl
kamacoder-solutions
kamacoder-solutions
main

搜索帮助