28. Find the Index of the First Occurrence in a String(找出字符串中第一个匹配项的下标)

问题描述

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。

问题分析

此问题时模式匹配问题可以采用暴力算法去查找,也可以使用kmp算法来进行查找。

代码

暴力算法:

int strStr(char *haystack, char * needle){
    int i,j;
    for(i = 0; haystack[i]!='\0'; i++){
        for(j = 0;needle[j]!='\0';j++){
            if(haystack[i+j]!=needle[j]){
                break;
            }
        }
        if(needle[j]=='\0'){
            return i;
        }
    }
    return -1;
}

kmp算法详解文章

提交结果截图

28. Find the Index of the First Occurrence in a String(找出字符串中第一个匹配项的下标)_第1张图片

你可能感兴趣的:(leetcode刷题日记,算法,数据结构,开发语言,leetcode)