Lintcode—13. 字符串查找(普通方法和KMP方法两种方法解决)

挺经典的一道问题,写下来供以后复习。

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

样例:

如果 source = "source" 和 target = "target",返回 -1

如果 source = "abcdabcdefg" 和 target = "bcd",返回 1


实现:

class Solution {
public:
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    /*int strStr(const char *source, const char *target) { //注释的这部分使用的是普通的搜索方法
        // write your code here
        if(source == NULL || target == NULL) 
            return -1;
        int m = strlen(source), n = strlen(target);
        if(m == 0 && n == 0)
            return 0;
        int result, label = 0;
        for(int i = 0; i < m; i++){
            int l = i, j = 0;
            while(source[l] == target[j] && j < n){
                l++, j++;
            }
            if(j == n){
                result = i;
                label = 1;
                break;
            }
        }
        if(label == 1)
            return result;
        else
            return -1;
    }*/
    
    int strStr(const char *source, const char *target){ //这部分是使用的KMP算法来解决
		if(source == NULL || target == NULL)
			return -1;
		int len = strlen(source);
		int len1 = strlen(target);
		if(len1 == 0)
		    return 0;
		if(len == 0)
			return -1;
		int i = 0;
		vector<int> next(len1);
		kmpNext(target, next);
		while(i < len){
			int j = 0;
			int l = i;
			while(j < len1 && source[l] == target[j]){
					l++, j++;
			}
			if(j == len1)
				//delete ;
				return i;
			else
				i += j - next[j];
		}
		return -1;
	}
	void kmpNext(const char *source, vector<int> &next){ //这里是求next[]
		next[0] = -1;
		int len = strlen(source);
		for(int i = 1; i < len; i++){
			int j = next[i - 1];
			while (j >= 0 && source[i - 1] != source[j])
				j = next[j];
			if(j >=0 && source[i - 1] == source[j])
				next[i] = j + 1;
			else
				next[i] = 0;
		}
	}
};
积累积累。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值