[LeetCode28] Implement strStr()

Implement strStr().

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

in Java, there is an API function name indexof(), it returns index within this string of the first occurrence of the specifiedsubstring. 

java 实现

public String strStr(String haystack, String needle) {
		if(haystack.length()<=0) return null;
        int i = haystack.indexOf(needle);
        if(i==-1) return null;
        else{
        	return haystack.substring(i);
        }
    }

another solution:

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;
    }

Below two solutions is overkill for interview.

third solution: rolling hash

http://blog.csdn.net/yanghua_kobe/article/details/8914970

fourth solution: KMP

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html


For c++

strightforward use point scan from begin to end, but this complexity is O(M*N)

char *strStr(char *haystack, char *needle) {
      if(!haystack || !needle) return NULL;
    int hlength = strlen(haystack);
    int nlength = strlen(needle);
    if(hlength<nlength) return NULL;
    for(int i=0; i<hlength-nlength+1;i++){
        char *p = &haystack[i];
        int j=0;
        for(;j<nlength;j++){
            if(*p == needle[j])
                p++;
            else
                break;
        }
        if(j == nlength)
            return &haystack[i];
    }
    return NULL;
    }


the best solution is KMP, complexity is O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值