博客
关于我
leetcode-28-Implement strStr()
阅读量:794 次
发布时间:2023-01-31

本文共 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 的长度。在大多数情况下,这是一个可接受的时间复杂度,适用于一般的字符串查找问题。

    解决代码

    #include 
    using 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。

    这种方法确保了代码的正确性和高效性,同时也处理了所有边界情况。

    转载地址:http://algyk.baihongyu.com/

    你可能感兴趣的文章
    LeetCode136.只出现一次的数字[异或运算典例]
    查看>>
    LeetCode13:罗马数字转整数
    查看>>
    leetcode190-颠倒二进制位
    查看>>
    leetcode191-打家劫舍
    查看>>
    leetcode23-合并K个升序链表
    查看>>
    leetcode231 判断一个给定的整数是否是2的n次幂
    查看>>
    leetcode238-除自身以外数组的乘积
    查看>>
    LeetCode240:Search a 2D Matrix II
    查看>>
    LeetCode268.缺失数字
    查看>>
    LeetCode331.验证二叉树的前序序列化
    查看>>
    leetcode380. Insert Delete GetRandom O(1)
    查看>>
    LeetCode502
    查看>>
    leetcode507
    查看>>
    LeetCode7.整数反转 JavaScript
    查看>>
    Leetcode: Group Anagrams
    查看>>
    Leetcode: Remove Duplicates from Sorted Array II
    查看>>
    Leetcode: Spiral Matrix II
    查看>>
    LeetCode: String to Integer (atoi)
    查看>>
    Leetcode:454. 4Sum II
    查看>>
    leetcode:Minimum Depth of Binary Tree【Python版】
    查看>>