简单模式匹配算法:
对主串的每一个字符作为子串开头,与要匹配的字符串进行匹配。对主串做大循环,每个字符开头子串长度的小循环,直到匹配成功或全部遍历完成为止。
版本一:
/*
* 简单模式匹配算法
* 输入主串和子串,在主串中匹配子串所在的位置;
* 如果主串存在子串,返回所在位置,负责返回-1。
* */
public class Main {
public static void main(String[] args) {
String S = "goodgoogle";
String T = "google";
System.out.println(Index(S,T));
}
private static int Index(String s, String t) {
int s_length = s.length();
int t_length = t.length();
char[] S = s.toCharArray();
char[] T = t.toCharArray();
int i = 0, j = 0;
while(i < s_length && j < t_length){
if(S[i] == T[j]){
++i;
++j;
}else{
i = i - j + 1;//i退回到上次匹配首位的下一位
j = 0;
}
}
if(j >= t_length)
return i-t_length;
else
return -1;
}
}
版本二:
/*
* 简单模式匹配算法
* 输入主串和子串,在主串中匹配子串所在的位置;
* 如果主串存在子串,返回所在位置,负责返回-1。
* */
public class Main {
public static void main(String[] args) {
String S = "goodgoogle";
String T = "google";
System.out.println(Index(S,T));
}
private static int Index(String s, String t) {
int s_length = s.length();
int t_length = t.length();
char[] S = s.toCharArray();
char[] T = t.toCharArray();
int k = 0, j = 0, i = 0;
for(i = 0; i < s_length; i++){
k = i;
j = 0;
for(j = 0; j < t_length; j++){
if(S[k] == T[j]){
++k;
}else{
break;
}
}
if(j == t_length){
return k-t_length;
}
}
return -1;
}
}