又到了快复试的时候了。遥想去年此时,心情忐忑不安,复试机试差点挂掉。当时考的是,联想输入法,想想都恐怖。这段时间写算法,顺便把那个给写了。也算最后纪念一下我的考研。我爱新学校,我也爱我的同学和老师,我很珍惜这次进入研究生院的机会。也希望那些此时和我当时一样忐忑不安的考生可以实现梦想!!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class TriTree {
public static void insert(TriNode root, String str) {
boolean end, find;
TriNode node = null;
for (int i = 0; i < str.length(); i++) {
end = false;
find = false;
List<TriNode> triLink = root.triLink;
if (i == (str.length() - 1))
end = true;
char ch = str.charAt(i);
Iterator<TriNode> iterator = triLink.iterator();
while (iterator.hasNext()) {
node = iterator.next();
if (node.ch == ch) {
find = true;
break;
}
}
if (find)
root = node;
else {
TriNode tri_node = new TriNode(ch);
triLink.add(tri_node);
root = tri_node;
}
if (end)
root.count++;
}
}
public static TriNode creat_TriTree(String fileName) {
File file = new File(fileName);
TriNode root = new TriNode();
try {
BufferedReader bf = new BufferedReader(new FileReader(file));
try {
String str = bf.readLine();
while (str != null) {
insert(root, str);
str = bf.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bf.close();
}
} catch (FileNotFoundException e) {
System.err.println("can't find the file in the location");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return root;
}
public static void traverse(TriNode root) {
char[] array = new char[20];
visit(array, 0, root.triLink.iterator(), 0);
}
public static void visit(char[] array, int len, Iterator<TriNode> iterator,
int count) {
if (!iterator.hasNext()) {
for (int i = 0; i < len; i++)
System.out.print(array[i]);
System.out.print(count);
System.out.println();
} else {
while (iterator.hasNext()) {
TriNode node = iterator.next();
array[len++] = node.ch;
visit(array, len, node.triLink.iterator(), node.count);
len--;
}
}
}
public static void hintSearch(TriNode root) {
Scanner in = new Scanner(System.in);
System.out.println("enter the word give the tip");
while (in.hasNext()) {
String str = in.nextLine();
TriNode node = null;
boolean find;
for (int i = 0; i < str.length(); i++) {
find = false;
char ch = str.charAt(i);
List<TriNode> triLink = root.triLink;
Iterator<TriNode> iterator = triLink.iterator();
while (iterator.hasNext()) {
node = iterator.next();
if (node.ch == ch)
{
find=true;
break;
}
}
if (find)
root = node;
}
traverse(root);//需要加一些小小的改进 很简单自己动手
}
}
}
////////////////////////////////////////////////////TriNode/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.util.LinkedList;
public class TriNode {
public int count=0;
public LinkedList<TriNode> triLink;
public char ch;
public TriNode(char ch)
{
this.ch=ch;
triLink=new LinkedList<TriNode>();
}
public TriNode()
{
triLink=new LinkedList<TriNode>();
}
}