当前位置:网站首页>实现strStr() II
实现strStr() II
2022-07-02 06:19:00 【沙子是沙子】
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack= "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack= "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
解决方法:
算法思想:
原strstr()函数。
strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
KMP算法。
参考:
http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
C++代码:
边栏推荐
- Flutter hybrid development: develop a simple quick start framework | developers say · dtalk
- TensorRT中的循环
- Learn about various joins in SQL and their differences
- No subject alternative DNS name matching updates. jenkins. IO found, the reason for the error and how to solve it
- WLAN相关知识点总结
- It is said that Kwai will pay for the Tiktok super fast version of the video? How can you miss this opportunity to collect wool?
- Redis---1. Data structure characteristics and operation
- Common means of modeling: combination
- From design delivery to development, easy and efficient!
- 日志(常用的日志框架)
猜你喜欢
随机推荐
500. Keyboard line
The real definition of open source software
深入了解JUC并发(一)什么是JUC
深入学习JVM底层(四):类文件结构
BGP报文详细解释
稀疏数组(非线性结构)
CUDA与Direct3D 一致性
Common means of modeling: combination
AttributeError: ‘str‘ object has no attribute ‘decode‘
Mech 3002 explanation
10 erreurs classiques de MySQL
Frequently asked questions about jetpack compose and material you
LeetCode 283. Move zero
利用传统方法(N-gram,HMM等)、神经网络方法(CNN,LSTM等)和预训练方法(Bert等)的中文分词任务实现
浅谈三点建议为所有已经毕业和终将毕业的同学
Ros2 --- lifecycle node summary
LeetCode 40. 组合总和 II
The difference between session and cookies
In depth understanding of JUC concurrency (I) what is JUC
谷歌出海创业加速器报名倒计时 3 天,创业人闯关指南提前收藏!