1.暴力解法:
public static void main(String[] args) {
String str1="iloveyousomuch";
String str2="youso";
int i = violence(str1, str2);
System.out.println(i);
}
public static int violence(String str1,String str2){
char[] s1=str1.toCharArray();
char[] s2=str2.toCharArray();
int i=0;
int j=0;
while(i<s1.length&&j<s2.length){
if(s1[i]==s2[j]){
i++;
j++;
}else{
//回溯
i=i-j+1;
j=0;
}
}
if(j==s2.length){
return i-j;
}else{
return -1;
}
}
2.KMP算法:
和C的next值不太一样??
//KMPSearch
public static int KMPSearch(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); i++) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)) {
j++;
}
if (j == str2.length()) {
return i - j + 1;
}
}
return -1;
}
//获取部分匹配值
public static int[] KMPNext(String str) {
//创建一个数组,保存部分匹配值
int[] next=new int[str.length()];
next[0]=0;
for(int i=1,j=0;i<str.length();i++){
while(j>0&&str.charAt(i)!=str.charAt(j)){
j=next[j-1];
}
if(str.charAt(i)==str.charAt(j)){
j++;
}
next[i]=j;
}
return next;
}