本文共 1446 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要编写一个函数来查找 haystack 中首次出现的 needle 子字符串的索引,如果 needle 不在 haystack 中,则返回 -1。
为了高效地解决这个问题,我们可以采用以下步骤:
处理特殊情况:
检查长度:
查找子字符串:
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;}
这种方法确保了代码的正确性和高效性,同时也处理了所有边界情况。
转载地址:http://algyk.baihongyu.com/