https:// www.bilibili.com/video/av53794167?from=search&seid=6694082725022421560
import java.util.Scanner; class TreeNode{ final static int MAX_SIZE = 26; char data; boolean isEnd = false ; TreeNode [] childs = new TreeNode[MAX_SIZE]; } public class TireTree{ //字典树的构建 a~z 转化为 0~25 输入一个值构建一次 public static void createTree(TreeNode node , String str) { char d [] = str.toCharArray(); for(int i = 0 ; i < d.length ; i++) { int loc = d[i] - 'a'; if(node.childs[loc]==null) { node.childs[loc] = new TreeNode(); //没有存在则创建 存在继续 node.childs[loc].data = d[i]; } node = node.childs[loc]; } } public static boolean find(TreeNode node,String str) { //没有找到 直接就返回false char a [] = str.toCharArray(); for(int i = 0 ; i < a.length ; i++) { int loc = a[i] - 'a'; if(node.childs[loc]==null) { return false; } node = node.childs[loc]; } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeNode root = new TreeNode(); while(sc.hasNext()) { String s = sc.nextLine(); createTree(root, s); System.out.println(find(root,s)); } } }
create的方法 省略其他