[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;}
- [LeetCode] Implement strstr() to Find a Substring in a String
- LeetCode Find All Anagrams in a String
- leetcode: Find All Anagrams in a String
- [LeetCode]Find All Anagrams in a String
- Leetcode Find All Anagrams in a String
- LeetCode : Find All Anagrams in a String
- leetcode[Find All Anagrams in a String]
- [leetcode][string] Implement strStr()
- Leetcode#28. Implement strStr()(String find()函数的用法)
- Find All Anagrams in a String Add to List
- leetcode 438. Find All Anagrams in a String
- LeetCode #438: Find All Anagrams in a String
- LeetCode 438. Find All Anagrams in a String
- LeetCode 438. Find All Anagrams in a String
- [leetcode] 438. Find All Anagrams in a String 解题报告
- 【leetcode】438. Find All Anagrams in a String【E】
- [leetcode]438. Find All Anagrams in a String
- leetcode刷题系列-Find All Anagrams in a String
- 如何将二维数组作为函数的参数传递
- 安卓webview中点击输入框没有响应的解决办法
- 我为什么要写blog
- [小说]魔王冢(51)突破口
- 8天学通MongoDB——第二天 细说增删查改
- [LeetCode] Implement strstr() to Find a Substring in a String
- 生成验证码
- 《TCPIP详解卷一》第一章学习笔记
- 【转载】ar,nm,objdump,objcopy
- Jenkins 自动部署 项目
- Qt 使用异或进行加密解密
- 全球jQuery的UI框架集锦,有国产DWZ框架入选
- class CAxWindow
- MP4 全介绍