package algorithm.algorithm.kmp;
/**
* @author AIMX_INFO
* @version 1.0
*/
public class ViolenceMatch {
public static void main(String[] args) {
String str1 = "abcdABCabcdAbcd~GG";
String str2 = "cd";
int index = violenceMatch(str1, str2);
System.out.println("index = " + index);
}
//暴力匹配算法实现
/**
* @param str1 原始字符串
* @param str2 要匹配的字符串
* @return 返回匹配的结果
*/
public static int violenceMatch(String str1, String str2) {
//将字符串转为字符数组
char[] c1 = str1.toCharArray();
char[] c2 = str2.toCharArray();
//记录长度
int c1Len = c1.length;
int c2Len = c2.length;
//定义变量 i , j 用于遍历
int i = 0;
int j = 0;
//遍历str1和str2循环比较
while (i < c1Len && j < c2Len) {
//如果第一个字符串的某一位和第二个字符串的第一位匹配,则判断后边是否继续匹配
if (c1[i] == c2[j]) {
i++;
j++;
} else {
//如果不匹配,则重置 i 和 j 重新开始匹配
i = i - (j - 1);
j = 0;
}
}
//循环结束后根据j的大小判断是否匹配到,如果匹配到返回索引
if (j == c2Len) {
return i - j;
} else {
//如果没有匹配到返回-1
return -1;
}
}
}
原文:https://www.cnblogs.com/mx-info/p/14883676.html