思路:其實就是逐個匹配,解法沒什麼亮點,我也不想說什麼。當然也可以把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<char *>(Str);
}
else
{
++Str;
}
}
return NULL;
}
照舊,給出main函數的調用:
#include<stdio.h>
#include<assert.h>
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; }