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

来源:互联网 发布:柠檬绿茶淘宝店 编辑:程序博客网 时间:2024/06/16 21:19

题目连接:http://leetcode.com/2010/10/implement-strstr-to-find-substring-in.html

思路:其实就是逐个匹配,解法没什么亮点,我也不想说什么。当然也可以把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;}

 

原创粉丝点击