JAVA字典树的查找

我的第一篇技术类博客,看周围朋友都把每天学习的东西记录在博客上,感觉还是挺好的。
那我也就以此作为一个开始吧。

需求是给定若干个字母,要求查找出这若干个字母组成的最长长度的单词。
字典树已生成。
public static String GenerateLongestWords(TriNode root, String src, String longestWord, int currentDepth, char[] word)
	{
		TriNode node = null;
		StringBuffer buffer = new StringBuffer(src);
		
		List<TriNode> triLink = root.triLink;
		Iterator<TriNode> iterator = triLink.iterator();
		
		while(iterator.hasNext())
		{
			node = iterator.next();
			if(node.ch == '#')
			{
				if(currentDepth > longestWord.length())
				{
					char[] word2 = new char[currentDepth];
					for(int j = 0 ; j< currentDepth ; j++)
						word2[j] = word[j];
					longestWord = String.copyValueOf(word2);
				}
			}
			else
			{
				//check whether we have a char available
				int i = src.indexOf(node.ch);
				if(i >= 0)
				{		
					word[currentDepth] = node.ch;
					//reduce the number of this char in our repository
					buffer.deleteCharAt(i);
					//following this path , DFS
					root = node;
					longestWord = GenerateLongestWords(root, buffer.toString(), longestWord, currentDepth+1, word);  
					buffer = new StringBuffer(src);
				}
				else 
				{
					//do nothing
				}
			}
		}
		return longestWord;
	}

src是可用的字母组成的字符串,longestWord最初的传入值为空

你可能感兴趣的:(java,J#)