当前位置:网站首页>实现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++代码:

边栏推荐
猜你喜欢
随机推荐
Web components series (VIII) -- custom component style settings
LeetCode 40. Combined sum II
BGP报文详细解释
Step by step | help you easily submit Google play data security form
LeetCode 47. 全排列 II
Google Play Academy 组队 PK 赛,正式开赛!
BGP 路由優選規則和通告原則
Pbootcms collection and warehousing tutorial quick collection release
锐捷EBGP 配置案例
深入学习JVM底层(四):类文件结构
Contest3147 - game 38 of 2021 Freshmen's personal training match_ E: Listen to songs and know music
稀疏数组(非线性结构)
Zhuanzhuanben - LAN construction - Notes
In depth understanding of JUC concurrency (I) what is JUC
Database learning summary 5
Invalid operation: Load into table ‘sources_orderdata‘ failed. Check ‘stl_load_errors‘ system table
Contest3145 - the 37th game of 2021 freshman individual training match_ H: Eat fish
Contest3147 - game 38 of 2021 Freshmen's personal training match_ A: chicken
I/o impressions from readers | prize collection winners list
LeetCode 90. 子集 II








