字符串匹配问题,可以通过3种方法进行求解:1.KMP算法 2.暴力法 3.调用String的indexOf()方法 (Java)

public class Main {
public static void main(String[] args) {
KMP kmp = new KMP();
int result1 = kmp.strStr(“mississippi”, “issipi”);
violence v=new violence();
int result2=v.strStr(“mississippi”, “issipi”);
UseMessage um=new UseMessage();
int result3=um.strStr(“mississippi”, “issipi”);
System.out.println("");
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}

class KMP {
public int strStr(String haystack, String needle) {
if (needle.equals("") || needle == null) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
int[] next = new int[needle.length()];//next为部分匹配表
next[0] = 0;//当字符串的长度为0时
for (int i = 1, j = 0; i < needle.length(); i++) {//遍历needle字符串
while (j > 0 && needle.charAt(i) != needle.charAt(j)) {//当不等的时候,死记,原理太难
j = next[j - 1];
}
if (needle.charAt(i) == needle.charAt(j)) {
j++;
}
next[i] = j;
}
for (int i = 0, j = 0; i < haystack.length(); i++) {//遍历haystack字符串
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {//和上面的不等的时候一样,原理太难,死记
j = next[j - 1];
}
if (haystack.charAt(i) == needle.charAt(j)) {
j++;
}
if (j == needle.length()) {
return i - j + 1;
}
}
return -1;
}
}

class violence {//暴力匹配
public int strStr(String haystack, String needle) {
if (needle.equals("") || needle == null) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
int i=0;
int j=0;
while(i if(haystack.charAt(i)needle.charAt(j)) {
i++;
j++;
}else {
i=i-j+1;
j=0;
}
}
if(j
needle.length()) {
return i-j;
}else {
return -1;
}
}
}

class UseMessage{
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}

你可能感兴趣的:(字符串匹配问题,可以通过3种方法进行求解:1.KMP算法 2.暴力法 3.调用String的indexOf()方法 (Java))