searchWords类
简介:实现单词的检索功能以及打印输入该单词出现的每个位置。
public class searchWords {
private String words;
private int[] next;
static List<Integer> list;
public searchWords(String words) {
this.words = words;
int n = words.length();
next = new int[n];
Next();
list = new ArrayList<Integer>();
}
文本的索引:search()
/*
*采用KMP算法,通过next[]数组,实现对文本的索引
*每匹配成功,将其位置加入list链表中
*/
public void search(String text) {//文本的索引
int n = text.length();
int m = words.length();
int i = 0, j = 0;
while (i < n) {
if (j == -1 || text.charAt(i) == words.charAt(j)) {
i++;
j++;//相等 同时后移
} else {
j = next[j];//不等,j取next数组中相应的最长相等前后缀长度
}
if (j == m) {//j与m相等,则匹配成功
list.add(i - m);//在list中加入相等的初位置
j = 0;
}
}
}
求next数组:Next()
/**
* 求最长相等前后缀长度:
*举例:字符串: abcabcmn ,对应next数组值
* a b c a b c m n
* -1 0 0 0 1 2 3 0
* nest数组关键点及重难点:回溯问题
* k j
* 望 江 望 江 楼 上 望 江 望 江 江 流
* 望 江 望 江 楼 上 望 江 望 江 江 流
* k
* 进行回溯,k=next[k]
*/
public void Next() {//求最长相等前后缀长度,放入Next数组中
int n = words.length();
if (n == 0) return;
if (n == 1) {
next[0] = -1;
return;
}
int j=0;
int k=-1;
next[0]=-1;
while(j<n-1) {
String s1;
String s2;
s1 = words.substring(0, j);
s2 = words.substring(n - j, n);
if (k==-1 || s1.equals(s2)){ //k为-1或比较的字符串相等时
j++;
k++;
next[j]=k;
}else{
k=next[k];
}
}
}
打印输出:print()
public void print(int[] row, int lines) {//打印输出
int[] Line = new int[100];
int[] Row = new int[100];
int n = list.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < lines; j++) {
if (list.get(i) < row[j + 1]) {
Line[i] = j + 1;
Row[i] = list.get(i) + 1 - row[j];
break;
}
}
}
System.out.println("出现的总次数:" + n + "\n");
for (int i = 0; i < n; i++) {
System.out.println("第" + (i + 1) + "次出现的位置为:" + "第" + Line[i] + "行 " + " 第" + Row[i] + "列");
}
}
}
test类
简介:该类主要是对文本的读取以及searchWords类中方法的调用
public class test {
static String fileName="./Text2.txt";
public static void main(String[] args) throws Exception {
StringBuffer re = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String text = br.readLine();
int lines = 0;
int[] Linewords = new int[100];
Linewords[0] = 0;
while (text != null) {
lines++;//记录行数
Linewords[lines] = Linewords[lines - 1] + text.length();//记录每一行前一共有多少字符
re.append(text);
text = br.readLine();
}
text = re.toString();
System.out.println("请输入需要查找的单词:");
Scanner scanner=new Scanner(System.in);
String str=scanner.next();
searchWords searchWords = new searchWords(str);
searchWords.search(text);
searchWords.print(Linewords, lines);
}
}
运行截图
这里我们先查找app这个单词
我们再查找abcab这个单词