Last active
January 16, 2023 14:28
-
-
Save honwhy/c0eb2b036ef64a176c33bd556e31dbd9 to your computer and use it in GitHub Desktop.
TrieTreeNode v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
import java.util.HashSet; | |
import java.util.LinkedHashMap; | |
import java.util.Set; | |
public class TrieTreeNode { | |
private char ch; | |
private Set<Long> ids = new HashSet<>(); | |
LinkedHashMap<Character, TrieTreeNode> children = new LinkedHashMap<>(); | |
public static void main(String[] args) { | |
TrieTreeNode root = new TrieTreeNode(); | |
root.ch = '/'; | |
root.addNode("天津滨海", 1L); | |
root.addNode("武汉天河", 2L); | |
Set<Long> ids = new HashSet<>(); | |
//root.search("天", new boolean[]{false}, ids); | |
root.search("天河", new boolean[]{false}, ids); | |
System.out.println(ids); | |
} | |
public void addNode(String name, Long id) { | |
char ch = name.charAt(0); | |
Character character = new Character(ch); | |
if (children.containsKey(character)) { | |
TrieTreeNode treeNode = children.get(character); | |
if (name.length() > 1) { | |
treeNode.addNode(name.substring(1), id); | |
} else { | |
treeNode.ids.add(id); | |
} | |
} else { | |
TrieTreeNode treeNode = new TrieTreeNode(); | |
treeNode.ch = ch; | |
children.put(character, treeNode); | |
if (name.length() > 1) { | |
treeNode.addNode(name.substring(1), id); | |
} else { | |
treeNode.ids.add(id); | |
} | |
} | |
} | |
public void search(String name, boolean[] flags,Set<Long> ids) { | |
char ch = name.charAt(0); | |
Character character = new Character(ch); | |
if (character.equals('#')) { | |
if (this.ids.size() > 0) { | |
ids.addAll(this.ids); | |
} | |
for (TrieTreeNode node : this.children.values()) { | |
node.search("#", flags, ids); | |
} | |
} else { | |
for (TrieTreeNode treeNode : children.values()) { | |
if (treeNode.ch == character) { | |
if (name.length() > 1) { | |
treeNode.search(name.substring(1), new boolean[]{true}, ids); | |
} else { | |
if (treeNode.ids.size() > 0) { | |
ids.addAll(treeNode.ids); | |
} | |
for (TrieTreeNode child : treeNode.children.values()) { | |
child.search("#", new boolean[]{true}, ids); | |
} | |
} | |
} else { | |
// keep in mind | |
if (!flags[0]) { | |
treeNode.search(name, new boolean[]{false}, ids); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment