KMP --LeetCode-- 4.20

 

28.实现strStr().

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

int strStr(char * haystack, char * needle){
    int i, j, flag = 0;
    int l1 = strlen(haystack);
    int l2 = strlen(needle);
    for(i = 0; i <= l1 - l2; i++){
        for(j = 0; j < l2; j++){
            if(haystack[i + j] != needle[j])break;
        }
        if(j == l2){
            flag = 1;
            break;
        }
    }
    if(flag == 0)return -1;
    else return i;
}

 

 

posted @ 2021-04-20 14:53  荣荣荣荣荣荣  阅读(32)  评论(0)    收藏  举报