Implement strStr()

【题目】

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

【题意】

     实现strstr(). 返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。
注:strstr()是c++中的一个函数

【思路】

一般方法:  假设原串的长度是n,匹配串的长度是m。对原串的每一个长度为m的字串都判断是否跟匹配串一致。总共有n-m个子串,所以算法时间复杂度为O((n-m)*m)=O(n*m),空间复杂度是O(1)。

实现:

public String strStr(String haystack, String needle) {
		if(haystack.length()<=0 && needle.length()>0) return null;
        for(int i=0;i<=haystack.length()-needle.length();i++){
        	boolean flag = true;
        	for(int j=0;j<needle.length();j++){
        		if(haystack.charAt(i+j)!=needle.charAt(j)){
        			flag = false;
        			break;
        		}
        	}
        	if(flag){
    			return haystack.substring(i);
    		}
        }
        return null;
    }
改进:克努特等人发明了KMP算法过后,关于strstr()函数的实现的时间复杂度就是线性的.对于KMP

public class Solution {

public String strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return null;
}
int[] next = getNext(needle);

int pS = 0, pH = pS, pN = 0;
while (pS + needle.length() <= haystack.length()) {
if (pN == needle.length()) {
return haystack.substring(pS);
} else if (haystack.charAt(pS + pH) == needle.charAt(pN)) {
pH++;
pN++;
} else if (next[pN + 1] == 0) {
pH = pN = 0;
pS++;
} else {
pH -= (pN – next[pN]);
pS += (pN – next[pN]);
pN = next[pN];
}
}
return null;
}

public static int[] getNext(String needle) {
int[] next = new int[needle.length() + 1];
next[0] = -1;
needle = '$' + needle;
for (int i = 1; i < needle.length(); i++) {
if (next[i – 1] == 0) {
next[i] = needle.charAt(i) == needle.charAt(1) ? 1 : 0;
} else {
int before = next[i – 1];
while (before != -1) {
if (needle.charAt(before + 1) == needle.charAt(i)) {
next[i] = before + 1;
break;
} else {
before = next[before];
}
}
}
}
return next;
}
}
kmp:http://blog.csdn.net/joylnwang/article/details/6778316/


你可能感兴趣的:(strstr,implement)