数据结构课程实践(3)-代码补充
—BF算法(朴素匹配算法)
算法思想:
设主串搜索起始位置为i
通过主串和子串一一对比
不满足时,子串回到初始位置,主串回到初始位置加一处
满足时,主串变为i+子串.length()-1处,子串回初始位置
继续开始匹配后面的字符
直到i>=主串.length()停止。
之后就是输出结果
代码实现:
1.运行类
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Action {
String xml;
String word;
Scanner scanner =new Scanner(System.in);
public void readTXT(){
try{
StringBuffer buffer = new StringBuffer();
BufferedReader bf= new BufferedReader(new FileReader("D:\\学生成绩管理系统数据文件\\article.txt"));
String s = null;
while((s = bf.readLine())!=null){
buffer.append(s.trim());
}
xml = buffer.toString();
System.out.println(xml);
}catch (IOException e){
System.out.println(e.getMessage());
}
}
public void start(){
int count;
readTXT();
System.out.println("请输入要查询的单词");
word=scanner.next();
count=bF(xml,word);
if(count==0){
System.out.println("未找到单词");
}
else{
System.out.println("一共找到"+count+"个");
}
}
public int bF(String a,String b){
int num=0;
int i=0;
int j=0;//子串移动
int t;//记录主串的开始位置
char []a1=a.toCharArray();
char []b1=b.toCharArray();
while(i<=a1.length){
t=i;
for(j=0;j<b1.length&&i<a1.length;j++)
{
if(a1[i]!=b1[j])
{
break;
}
else{
i++;
}
}
if((i-t)>=b1.length){
location(t,b);
num++;
i=t+b1.length-1;
}
else {
i=t+1;
}
}
return num;
}
public void location(int x,String word){
int t=x+word.length()-1;
System.out.println("单词位置:"+x+"~"+t);
}
}
2.主类
public class Main {
public static void main(String[]args){
Action action=new Action();
action.start();
}
}