字符串查找

题目:

 对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回-1

一开始看到这个题模就想到了书上的BF暴力搜索算法,虽然通过了但是很浪费时间。

然后学了一下kmp算法,觉得很高效。

//BF
int strStr(const char *source, const char *target) {
        // write your code here
            if((source == NULL) || (target == NULL))
             	{
             	    return -1;
             	}
        	int lenghta = strlen(source);
         	int lengthb = strlen(target);
         	int i,j;i = j = 0;
         	while((source[i] != '\0') &&(target[j] != '\0'))
         	{
         		if(source[i] == target[j])
         		{
         			i++;
         			j++;
         		}
         		else
         		{
         			i = i - j + 1;
         			j = 0;
         		}
         	}
         	if(target[j] == '\0')
         	{
         		return i - j;
         	}
         	else
         	{
         		return -1;
         	}
    }
KMP
 void prehandle(const char *a,int b[])
    {
    	int length = strlen(a);
    	int j = 0;
    	b[j] = -1;
    	int k = -1;
    	for(int i = 0;i < length;i++)
    	{
    		if(k == -1 || a[j] == a[k])
    		{
    			k++;
    			j++;
    			b[j] = k;
    		}
    		else
    		{
    			k = b[k];
    		}
    	}
    }
    int strStr(const char *source, const char *target) {
        // write your code here
        	if((source == NULL) || (target == NULL))
             	{
             	    return -1;
             	}
           int ls,lt;
           ls = strlen(source);lt = strlen(target);
           if( lt == 0)
           {
               return 0;
           }
           int next[lt];
           prehandle(target,next);
           int i,j;i = j = 0;
           while((source[i] != '\0') && (target[j] != '\0'))
           {
           		if(source[i] == target[j])
           		{
           			i++;
           			j++;
           		}
           		else
           		{
           			j = next[j];
           			if(j == -1)
           			{
           				j++;
           				i++;
           			}
           		}
           }
           if(target[j] == '\0')
           {
        		return i - lt;
           }
           else
           {
           		return -1;
           }
    }
};

kmp 算法其实主要是比较是S[ i ]不变不用重新比较,而且T[ j ]也把重复的部分省去了。

该算法的难点在于当T[ j ]匹配失败后回溯到哪里。详见http://blog.youkuaiyun.com/starstar1992/article/details/54913261

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值