Horspool算法(java)随机生成字符串
2021-02-19 06:18
标签:ima return 运行时间 color turn ble next mil none 结果(跑个时间) Horspool算法(java)随机生成字符串 标签:ima return 运行时间 color turn ble next mil none 原文地址:https://www.cnblogs.com/shish/p/12685731.htmljava代码
import java.util.Scanner;
public class Horspool {
public static void ShiftTable(char[] p, int[] table){
for (int i = 0; i ) {
table[i] = p.length;
}
for (int i = 0; i ) {
table[p[i] -‘A‘] = p.length - 1 - i;
}
}
public static int HorspoolMatching(char[] text, char[] template,int[] table){
ShiftTable(template, table);
int i = template.length - 1;
while(i text.length){
int k = 0;
while(k k])
k++;
if(k == template.length)
return i - template.length +1;
else
i += table[text[i]-‘A‘];
}
return -1;
}// Horspool算法
public static int Matching(char[] text, char[] template){
for (int i = 0; i ) {
int k = 0;
for (; k ) {
if(text[i+k] != template[k])
break;
}
if(k == template.length)
return i;
}
return -1;
} // 蛮力法
public static String getRandomString(long length) {
System.out.println("正在生成文本");
StringBuffer sb = new StringBuffer();
for (int i = 0; i ) {
long result = 0;
result = Math.round(Math.random() * 25 + 97);
sb.append(String.valueOf((char) result));
}
System.out.println("成功生成");
return sb.toString();
} // 随机生成字符串
public static void main(String[] args) {
int[] table = new int[26];
Scanner in = new Scanner(System.in);
// System.out.println("输入匹配的文本");
// String te = in.nextLine();
// System.out.println("输入匹配的模板");
// String t = in.nextLine();
String te = getRandomString(100000000);
String t = getRandomString(10000);
te = te.toUpperCase();
t = t.toUpperCase();
char[] text = te.toCharArray();
char[] template = t.toCharArray();
System.out.println("---------Horspool算法-----------");
long start1=System.currentTimeMillis();
int pos1 = HorspoolMatching(text, template, table);
long end1=System.currentTimeMillis(); //获取结束时间
if(pos1 == -1)
System.out.println("没有匹配的字符串!");
else
System.out.println("存在匹配的字符串,初始位置为:" + pos1);
System.out.println("程序运行时间: " + (end1 - start1) + "ms");
System.out.println("------------蛮力法--------------");
long start2=System.currentTimeMillis();
int pos2 = Matching(text, template);
long end2=System.currentTimeMillis(); //获取结束时间
if(pos2 == -1)
System.out.println("没有匹配的字符串!");
else
System.out.println("存在匹配的字符串,初始位置为:" + pos2);
System.out.println("程序运行时间: "+(end2 - start2)+"ms");
}
}
文章标题:Horspool算法(java)随机生成字符串
文章链接:http://soscw.com/index.php/essay/57400.html