java Trie实现英文单词查找树 搜索自动提示

原理解释文章:https://blog.csdn.net/beiyetengqing/article/details/7856113
代码应用:
wordTrie.txt(工具类):

package com.xq.algorithm;

import java.util.ArrayList;
import java.util.List;




/**
 * 
 * <p>Title:</p>
 * <p>Description: 单词Trie树
 * </p>
 * @createDate:2013-10-17
 * @author xq
 * @version 1.0
 */
public class WordTrie {
	/**trie树根*/
	private TrieNode root = new TrieNode();
	
	/**英文字符串正则匹配*/
	static String  englishPattern="^[A-Za-z]+$";
	/**中文正则匹配*/
	static String chinesePattern="[\u4e00-\u9fa5]";
	
	static int ARRAY_LENGTH=26;
	
	static String zeroString="";
	
	/**
	 * 
	* @Title: addWord
	* @Description: add word
	* @param @param word    
	* @return void   
	* @throws
	 */
	public void addWord(String word) {
		if(word==null || "".equals(word.trim())){
			throw new IllegalArgumentException("word can not be null!");
		}
		if(!word.matches(englishPattern)){
			throw new IllegalArgumentException("word must be english!");
		}
		addWord(root, word);
	}

	/**
	 * 
	* @Title: addWord
	* @Description:add word to node
	* @param @param node
	* @param @param word    
	* @return void   
	* @throws
	 */
	private void addWord(TrieNode node, String word) {
		if (word.length() == 0) { // if all characters of the word has been
			// added
			node.count++;
			node.nodeState=1;
		} else {
			node.prefixCount++;
			char c = word.charAt(0);
			c = Character.toLowerCase(c);
			int index = c - 'a';
			if(index>=0 && index<ARRAY_LENGTH){
				if (node.next[index] == null) { 
					node.next[index] = new TrieNode();
				}
				// go the the next character
				addWord(node.next[index], word.substring(1));
			}
			 
		}
	}
	
	/**
	 * 
	* @Title: prefixSearchWord
	* @Description: 前缀搜索
	* @param @param word
	* @param @return    
	* @return List<String>   
	* @throws
	 */
	public List<String> prefixSearchWord(String word){
		if(word==null || "".equals(word.trim())){
			return new ArrayList<String>();
		}
		if(!word.matches(englishPattern)){
			return new ArrayList<String>();
		}
		char c = word.charAt(0);
		c = Character.toLowerCase(c);
		int index = c - 'a';
		if(root.next!=null && root.next[index]!=null){
			return depthSearch(root.next[index],new ArrayList<String>(),word.substring(1),""+c,word);
		}else{
			return new ArrayList<String>();
		}
	}
	
	/**
	 * 
	* @Title: searchWord
	* @Description: 搜索单词,以a-z为根,分别向下递归搜索
	* @param @param word
	* @param @return    
	* @return List<String>   
	* @throws
	 */
	public List<String> searchWord(String word){
		if(word==null || "".equals(word.trim())){
			return new ArrayList<String>();
		}
		if(!word.matches(englishPattern)){
			return new ArrayList<String>();
		}
		char c = word.charAt(0);
		c = Character.toLowerCase(c);
		int index = c - 'a';
		List<String> list=new ArrayList<String>();
		if(root.next==null){
			return list;
		}
		for(int i=0;i<ARRAY_LENGTH;i++){
			int j='a'+i;
			char temp=(char)j;
			if(root.next[i]!=null){
				if(index==i){
					fullSearch(root.next[i],list,word.substring(1),""+temp,word);
				}else{
					fullSearch(root.next[i],list,word,""+temp,word);
				}
			}
		}
		return list;
	}
	
	/**
	 * 
	* @Title: fullSearch
	* @Description: 匹配到对应的字母,则以该字母为字根,继续匹配完所有的单词。
	* @param @param node
	* @param @param list 保存搜索到的字符串
	* @param @param word 搜索的单词.匹配到第一个则减去一个第一个,连续匹配,直到word为空串.若没有连续匹配,则恢复到原串。
	* @param @param matchedWord 匹配到的单词
	* @param @return    
	* @return List<String>   
	* @throws
	 */
	private List<String> fullSearch(TrieNode node,List<String> list,String word,String matchedWord,String inputWord){
		if(node.nodeState==1  && word.length()==0){
			list.add(matchedWord);
		}
		if(word.length() != 0){
			char c = word.charAt(0);
			c = Character.toLowerCase(c);
			int index = c - 'a';
			for(int i=0;i<ARRAY_LENGTH;i++){
				if(node.next[i]!=null){
					int j='a'+i;
					char temp=(char)j;
					if(index==i){
						//连续匹配
						fullSearch(node.next[i], list, word.substring(1), matchedWord+temp,inputWord);
					}else{
						//未连续匹配,则重新匹配
						fullSearch(node.next[i], list, inputWord, matchedWord+temp,inputWord);
					}
				}
			}
		}else{
			if(node.prefixCount>0){
				for(int i=0;i<ARRAY_LENGTH;i++){
					if(node.next[i]!=null){
						int j='a'+i;
						char temp=(char)j;
						fullSearch(node.next[i], list, zeroString, matchedWord+temp,inputWord);
					}
				}
			}
		}
		return list;
	}
	
	/**
	 * 
	* @Title: depthSearch
	* @Description: 深度遍历子树
	* @param @param node
	* @param @param list 保存搜索到的字符串
	* @param @param word 搜索的单词.匹配到第一个则减去一个第一个,连续匹配,直到word为空串.若没有连续匹配,则恢复到原串。
	* @param @param matchedWord 匹配到的单词
	* @param @return    
	* @return List<String>   
	* @throws
	 */
	private List<String> depthSearch(TrieNode node,List<String> list,String word,String matchedWord,String inputWord){
		if(node.nodeState==1 && word.length()==0){
			list.add(matchedWord);
		}
		if(word.length() != 0){
			char c = word.charAt(0);
			c = Character.toLowerCase(c);
			int index = c - 'a';
			//继续完全匹配,直到word为空串,否则未找到
			if(node.next[index]!=null){
				depthSearch(node.next[index], list, word.substring(1), matchedWord+c,inputWord);
			}
		}else{
			if(node.prefixCount>0){//若匹配单词结束,但是trie中的单词并没有完全找到,需继续找到trie中的单词结束.
				//node.prefixCount>0表示trie中的单词还未结束
				for(int i=0;i<ARRAY_LENGTH;i++){
					if(node.next[i]!=null){
						int j='a'+i;
						char temp=(char)j;
						depthSearch(node.next[i], list, zeroString, matchedWord+temp,inputWord);
					}
				}
			}
		}
		return list;
	}
	
	class TrieNode {
		/**
		 * trie tree word count
		 */
		int count=0;
		
		/**
		 * trie tree prefix count
		 */
		int prefixCount=0;
		
		/**
		 * 指向各个子树的指针,存储26个字母[a-z]
		 */
		TrieNode[] next=new TrieNode[26];

		/**
		 * 当前TrieNode状态 ,默认 0 , 1表示从根节点到当前节点的路径表示一个词
		 */
		int nodeState = 0;
		
		TrieNode(){
			count=0;
			prefixCount=0;
			next=new TrieNode[26];
			nodeState = 0;
		}
	}
}

测试类:

package com.xq.algorithm;

import java.util.List;

public class WordTrieMain {

	public static void main(String[] args){
		test();
	}
	
	public static void test1(){
		WordTrie trie=new WordTrie();
		
		trie.addWord("ibiyzbi");

		System.out.println("----------------------------------------");
		List<String> words=trie.searchWord("bi");
		for(String s: words){
			System.out.println(s);
		}
	}
	
	public static void test(){
		WordTrie trie=new WordTrie();
		trie.addWord("abi");
		trie.addWord("ai");
		trie.addWord("aqi");
		trie.addWord("biiiyou");
		trie.addWord("dqdi");
		trie.addWord("ji");
		trie.addWord("li");
		trie.addWord("liqing");
		trie.addWord("liqq");
		trie.addWord("liqqq");
		trie.addWord("qi");
		trie.addWord("qibi");
		trie.addWord("i");
		trie.addWord("ibiyzbi");
		List<String> list=trie.prefixSearchWord("li");
		for(String s: list){
			System.out.println(s);
		}
		System.out.println("----------------------------------------");
		List<String> li=trie.searchWord("i");
		for(String s: li){
			System.out.println(s);
		}
		System.out.println("----------------------------------------");
		List<String> words=trie.searchWord("bi");
		for(String s: words){
			System.out.println(s);
		}
		
		System.out.println("----------------------------------------");
		List<String> lst=trie.searchWord("q");
		for(String s: lst){
			System.out.println(s);
		}
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Trie字典Java代码实现可以分为以下几部分: 1. 定义Trie节点类,包含children数组和isEndOfWord标识,用于表示是否是单词的结尾。 2. 定义Trie类,包含插入、查找和删除操作。 3. 在Trie类中实现插入操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果不存在则新建节点。 4. 在Trie类中实现查找操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则说明字符串是单词。 5. 在Trie类中实现删除操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则将其设为false,并删除空节点。 如果需要完整代码和注释请告诉我。 ### 回答2: Trie(字典)是一种常用的数据结构,用于高效地存储和查找字符串。下面是Trie字典Java代码实现,用于返回单词。 ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 字母表的大小为26 isEndOfWord = false; } public void insert(String word) { TrieNode curr = this; for (char c : word.toCharArray()) { if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String prefix) { TrieNode curr = this; for (char c : prefix.toCharArray()) { if (curr.children[c - 'a'] == null) { return null; } curr = curr.children[c - 'a']; } return curr; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { root.insert(word); } public boolean search(String word) { return root.search(word); } public boolean startsWith(String prefix) { return root.startsWith(prefix); } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.search("apple")); // 输出:true System.out.println(trie.startsWith("app")); // 输出:true System.out.println(trie.search("banana")); // 输出:false } } ``` 以上代码中,`TrieNode`表示Trie的节点,`Trie`表示Trie的结构。其中`TrieNode`类包含了插入单词、查找单词(完全匹配)以及查找前缀的功能。`Trie`类则是对外提供插入、查找单词和前缀的方法。 在`main`方法中,我们演示了如何使用`Trie`类来插入和查找单词。首先,我们插入了两个单词"apple"和"app"。然后分别调用`search`方法来查找"apple"和"banana",以及`startsWith`方法来查找以"app"开头的单词。最后,打印出对应的结果,即是否找到了对应的单词或前缀。 以上是Trie字典Java代码实现,用于返回单词。 ### 回答3: Trie字典是一种经典的数据结构,用于高效地存储和查找字符串集合。下面是一个基于JavaTrie字典的代码实现,可以实现返回单词的功能: ```java class TrieNode { private final int ALPHABET_SIZE = 26; private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current != null && current.isEndOfWord; } public List<String> getAllWords() { List<String> result = new ArrayList<>(); TrieNode current = root; StringBuilder sb = new StringBuilder(); getAllWordsUtil(current, sb, result); return result; } private void getAllWordsUtil(TrieNode node, StringBuilder sb, List<String> result) { if (node == null) { return; } if (node.isEndOfWord) { result.add(sb.toString()); } for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { sb.append((char)('a' + i)); getAllWordsUtil(node.children[i], sb, result); sb.deleteCharAt(sb.length() - 1); } } } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); String[] words = {"hello", "world", "java", "programming"}; for (String word : words) { trie.insert(word); } List<String> allWords = trie.getAllWords(); System.out.println("All words in trie: " + allWords); } } ``` 上述代码中,TrieNode类表示字典的节点,包括一个指向子节点的数组和一个标记,用于表示节点是否是某个单词的结尾。Trie类封装了字典的操作,包括插入单词、查找单词和返回所有单词的功能。在代码的主函数中,我们创建一个Trie对象并插入一些单词,然后调用getAllWords()方法返回字典中的所有单词。最后,打印出返回的单词列表。 希望以上解答对您有所帮助,如有更多疑问,请继续追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值