From 499f627841bd0e3c1709c61d28b34057411111ee Mon Sep 17 00:00:00 2001 From: aofall <10182210+aofall@users.noreply.github.com> Date: Wed, 11 Dec 2024 19:27:26 +0800 Subject: [PATCH] feat(string/trie.md): Add Java code (#6044) * feat(string/trie.md): Add Java code * style: format markdown files with remark-lint * reformat * style: format markdown files with remark-lint * reformat * style: format markdown files with remark-lint * reformat * update struct --------- Co-authored-by: 24OI-bot <15963390+24OI-bot@users.noreply.github.com> --- docs/string/trie.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/string/trie.md b/docs/string/trie.md index 8b3dd92e47fae..7db466ef7ef31 100644 --- a/docs/string/trie.md +++ b/docs/string/trie.md @@ -74,6 +74,42 @@ trie 的结构非常好懂,我们用 $\delta(u,c)$ 表示结点 $u$ 的 $c$ return self.exist[p] ``` +=== "Java" + ```java + public class Trie { + + int[][] tree = new int[10000][26]; + int cnt = 0; + boolean[] end = new boolean[10000]; + + public void insert(String word) { + int p = 0; + char[] chars = word.toCharArray(); + for (int i = 0; i < chars.length; i++) { + int c = chars[i] - 'a'; + if (tree[p][c] == 0) { + tree[p][c] = ++cnt; + } + p = tree[p][c]; + } + end[p] = true; + } + + public boolean find(String word) { + int p = 0; + char[] chars = word.toCharArray(); + for (int i = 0; i < chars.length; i++) { + int c = chars[i] - 'a'; + if (tree[p][c] == 0) { + return false; + } + p = tree[p][c]; + } + return end[p]; + } + } + ``` + ## 应用 ### 检索字符串