[LeetCode] Implement strstr() to Find a Substring in a String

2014-11-23 21:54:15 · 作者: · 浏览: 13
思路:其实就是逐个匹配,解法没什么亮点,我也不想说什么。当然也可以把IsMatch嵌入到StrStr里面,可以减少函数调用的开销,但是可读性可能就会降低了。
1、当前字符匹配,则返回当前字符。
2、当前字符不匹配,则往前跳一个。
其实和A String Replace Problem 类似的思想,核心参考代码:
bool IsMatch(const char *Str, const char *Pattern)  
{  
    assert(Str && Pattern);  
    while(*Pattern != '\0')  
    {  
        if(*Str++ != *Pattern++)  
        {  
            return false;  
        }  
    }  
    return true;  
}  
  
char* StrStr(const char *Str, const char *Pattern)  
{  
    assert(Str && Pattern);  
    while(*Str != '\0')  
    {  
        if(IsMatch(Str, Pattern))  
        {  
            return const_cast
(Str); } else { ++Str; } } return NULL; }

照旧,给出main函数的调用:
#include  
#include  
int main()  
{  
    const int MAX_N = 50;  
    char Str[MAX_N];  
    char Pattern[MAX_N];  
    char* Ans = NULL;  
    while(gets(Str) && gets(Pattern))  
    {  
        Ans = StrStr(Str, Pattern);  
        if(Ans)  
        {  
            puts(Ans);  
        }  
        else  
        {  
            printf("不是子串\n");  
        }  
    }  

return 1;
}