package com.liyiwen.TestTrie; /** * Created by dell on 2015/7/12. */ public class Trie { private int size = 26; private TrieNode root; private class TrieNode{ private int passCount; private boolean isEnd; private TrieNode[] nodes; private char val; public TrieNode(){ passCount = 1; isEnd = false; nodes = new TrieNode[size]; } } public static Trie getInstance(){ return new Trie(); } private Trie(){ root = new TrieNode(); } public void insert(String str){ if (null == str || str.isEmpty()){ return; } TrieNode node = root; char[] charArray = str.toCharArray(); for (char val : charArray){ int index = val - 'a'; if (null == node.nodes[index]){ node.nodes[index] = new TrieNode(); node.nodes[index].val = val; }else{ node.nodes[index].passCount++; } node = node.nodes[index]; } node.isEnd = true; } public boolean hasString(String extStr){ if (null == extStr || extStr.isEmpty()) return false; char[] chars = extStr.toCharArray(); TrieNode node = root; for (char val : chars) { int index = val - 'a'; if (null == node.nodes[index]) { return false; } else { node = node.nodes[index]; } } return node.isEnd; } public int preCount(String pex){ if (null == pex || pex.isEmpty()) return 0; TrieNode node = root; char[] chars = pex.toCharArray(); for (char val : chars){ int index = val - 'a'; if (null == node.nodes[index]){ return 0; }else { node = node.nodes[index]; } } return node.passCount; } private void preOrderTraverse(TrieNode node){ if (node != null) { System.out.print(node.val + "-"); for (TrieNode sonNode : node.nodes) { preOrderTraverse(sonNode); } } } private TrieNode getRoot(){ return root; } public void preOrderTraverse(){ preOrderTraverse(getRoot()); } }
Trie树的java实现
最新推荐文章于 2023-02-12 23:05:36 发布