https://oj.leetcode.com/problems/implement-strstr/
字符串匹配在java中inexof()能解决这个问题。
public class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
当然写一个KMP算法才是真正的练习:
public class Solution {
public int strStr(String haystack, String needle) {
int hlen=haystack.length();
int nlen=needle.length();
if(needle.equals("")){return 0;}
if(haystack.equals("")){return -1;}
int []next=getNext(needle);
int i=0;
int j=0;
while(i<hlen&&j<nlen){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
j=next[j];
}
}
if(j==nlen){
return i-j;
}else
return -1;
}
public static int[] getNext(String str){
int len=str.length();
int[]ret=new int[len];
ret[0]=-1;
int k=-1;
int j=0;
while(j<len-1){
if(k==-1||str.charAt(j)==str.charAt(k)){
++k;
++j;
ret[j]=k;
}else{
k=ret[k];
}
}
return ret;
}
}