动手实现C++中strstr(haystack, needle)函数

该函数用于判断needle是否为haystack的子串,如果是,则返回needle在haystack中首次出现的索引。如果不存在,返回-1。

int strstr(string haystack, string needle)
{
    int h = haystack.size();
    int n = needle.size();
    if(!n)	return 0;
    int i;
    // h - n + 1 是指needle只可能存在于haystack[0...h-n]中的某个位置
    for(i = 0; i < h - n + 1; i++){
        int j = 0;
        for(; j < n; j++){
            if(haystack[i + j] != needle[j])
                break;
        }
        if(j == n)	return i;
    }
    return -1;
}

上面代码的主要是暴力解法,遍历每一种可能,直到找到第一个满足条件的结果。

posted @ 2018-02-09 09:15  一棵球和一枝猪  阅读(575)  评论(0编辑  收藏  举报