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/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值