
leetcode-28-Implement strStr()
发布日期:2025-04-05 02:46:18
浏览次数:12
分类:精选文章
本文共 1446 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要编写一个函数来查找 haystack 中首次出现的 needle 子字符串的索引,如果 needle 不在 haystack 中,则返回 -1。
方法思路
为了高效地解决这个问题,我们可以采用以下步骤:
处理特殊情况:
- 如果 needle 为空字符串,返回 0,因为空字符串可以被认为是任何字符串的子字符串。
- 如果 haystack 为空字符串,而 needle 不为空,返回 -1,因为空字符串无法包含非空子字符串。
- 如果 needle 和 haystack 都为空字符串,返回 0。
检查长度:
- 如果 haystack 的长度小于 needle 的长度,返回 -1,因为 needle 无法出现在 haystack 中。
查找子字符串:
- 遍历 haystack,从第一个字符开始,直到 haystack 可以包含 needle 的最后一个位置。
- 使用
substr
方法提取子字符串进行比较,如果找到匹配项,返回当前索引;否则,遍历结束后返回 -1。
这种方法的时间复杂度为 O(n*m),其中 n 是 haystack 的长度,m 是 needle 的长度。在大多数情况下,这是一个可接受的时间复杂度,适用于一般的字符串查找问题。
解决代码
#includeusing namespace std;int strStr(string haystack, string needle) { // 如果 needle 为空,返回 0 if (needle.empty()) { return 0; } // 如果 haystack 为空,则不能包含 needle,返回 -1 if (haystack.empty()) { return -1; } // 检查 haystack 的长度是否大于等于 needle 的长度 int haystackLength = haystack.length(); int needleLength = needle.length(); if (haystackLength < needleLength) { return -1; } // 遍历 haystack, 从开始到 haystackLength - needleLength 的位置 int maxIndex = haystackLength - needleLength; for (int i = 0; i <= maxIndex; ++i) { string sub = haystack.substr(i, needleLength); if (sub == needle) { return i; } } // 如果遍历完都没找到,返回 -1 return -1;}
代码解释
- 处理特殊情况:检查针是否为空字符串,根据情况返回相应的值。
- 长度检查:如果 haystack 的长度小于 needle 的长度,直接返回 -1。
- 遍历查找:从 haystack 的起始位置开始,逐步提取子字符串进行比较,找到匹配项后返回当前索引。遍历结束后如果没有找到,返回 -1。
这种方法确保了代码的正确性和高效性,同时也处理了所有边界情况。
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年05月03日 08时02分17秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
leetcode190-颠倒二进制位
2025-04-05
leetcode191-打家劫舍
2025-04-05
leetcode23-合并K个升序链表
2025-04-05
leetcode231 判断一个给定的整数是否是2的n次幂
2025-04-05
leetcode238-除自身以外数组的乘积
2025-04-05
LeetCode240:Search a 2D Matrix II
2025-04-05
LeetCode268.缺失数字
2025-04-05
LeetCode331.验证二叉树的前序序列化
2025-04-05
leetcode380. Insert Delete GetRandom O(1)
2025-04-05
LeetCode502
2025-04-05
leetcode507
2025-04-05
LeetCode7.整数反转 JavaScript
2025-04-05
Leetcode: Group Anagrams
2025-04-05
Leetcode: Spiral Matrix II
2025-04-05
LeetCode: String to Integer (atoi)
2025-04-05
Leetcode:454. 4Sum II
2025-04-05
LeetCode:Restore IP Addresses
2025-04-05
LeetCode:Subsets I II
2025-04-05