Leetcode 28. Implement strStr()

2017-04-09  本文已影响0人  persistent100

题目

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

分析

判断一个字符串是不是另一个字符串的子串。只需从前向后挨个判断是否匹配即可。而且要注意两个字符串分别为空的情况

int strStr(char* haystack, char* needle) {
    int p1=0,p2=0,p3=0;
    while(haystack[p1]!='\0')
    {
        p3=p1;
        while(haystack[p3]!='\0'&&haystack[p3]==needle[p2])
        {
            p3++;
            p2++;
        }
        if(needle[p2]=='\0')
            return p1;
        else
        {
            p1++;
            p2=0;
        }
    }
    if(needle[0]=='\0')
        return 0;
    else
        return -1;
}
上一篇 下一篇

猜你喜欢

热点阅读