编译原理第一次实验:采用KMP算法查询.cpp文件中的某个单词
package com.zhang;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CheckedOutputStream;
/**
* @Author:Zpg
* @Date:2020/3/8 12:02
* @Version:1.0
* @Description: 这是KMP算法部分
*/
public class KMP {
public static List kmp1(String s, String pat) throws Exception {//str文本串 dest 模式串
List list = new ArrayList();
int[] next = next(pat);
if (s.length() < pat.length()){
return null;
}
for (int i = 0,j = 0; i < s.length(); i++) {
if (s.charAt(i) != pat.charAt(j)){
// next数组第一个为-1时的操作
j = next[j];
if (j == -1){
j++;
}
}
if (s.charAt(i) == pat.charAt(j)){
j++;
}
if (j == pat.length()){
// 将匹配到的字符串的开始下标添加到list中。
list.add(i-j+1);
j = 0;
}
}
return list;
}
// 求解next数组
public static int[] next(String p) throws Exception{
int[] next = new int[p.length()];
int k = 0;
int j = 1;
next[0] = -1;
next[1] = 0;
while (j < p.length() - 1){
if (p.charAt(j) == p.charAt(k)){
next[j+1] = k+1;
k++;
j++;
}else if(k == 0){
next[j+1] = k;
j++;
}else
k = next[k];
}
}
return next;
}
}
package com.zhang;
import java.io.*;
import java.util.List;
/**
* @Author:Zpg
* @Date:2020/3/8 13:44
* @Version:1.0
* @Description:
*/
public class KmpTest {
public static void main(String[] args) {
test();
}
public static void test() {
File file = new File("D:\\VSxiangmu\\个数.cpp");
try {
// 读取文件内容,并且按行读取
FileReader fr = new FileReader(file);
BufferedReader r = new BufferedReader(fr);
int lineCount = 1;
String pattern = "count";
String str;
List indexes; // 匹配到字符串的位置
System.out.println("行数"+" "+"位置");
while (((str = r.readLine()) != null)) {
// 如果匹配到字符串,则打印行数和位置
indexes = KMP.kmp1(str, pattern);
if (indexes == null){
continue;
}
if (!indexes.isEmpty()){
for (Object index : indexes) {
System.out.println(lineCount + " "+index);
}
}
lineCount++;
}
r.close();
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
实验结果