给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例 1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
+ (NSInteger)hy_strStr:(NSString *)haystack needle:(NSString *)needle {
// 如果 needle 为空,则返回 0
if (needle.length == 0) {
return 0;
}
// 如果 haystack 长度小于 needle 长度,则直接返回 -1
if (haystack.length < needle.length) {
return -1;
}
NSInteger n = haystack.length;
NSInteger m = needle.length;
// 在 haystack 中滑动窗口,并比较每个子串是否等于 needle
for (NSInteger i = 0; i <= n - m; i++) {
NSString *substring = [haystack substringWithRange:NSMakeRange(i, m)];
if ([substring isEqualToString:needle]) {
return i;
}
}
// 如果找不到匹配项,则返回 -1
return -1;
}
该算法使用滑动窗口方法,在输入字符串 haystack 中查找字符串 needle 的第一个匹配项的下标。
我们首先检查 needle 是否为空。如果为空,则 haystack 中的任何位置都是匹配项,因此我们返回 0。
然后,我们检查 haystack 的长度是否小于 needle 的长度。如果是,则 needle 没有可能成为 haystack 的子字符串,因此我们直接返回 -1。
接下来,我们使用滑动窗口方法在 haystack 中遍历每个子字符串,并比较其是否与 needle 相等。如果找到匹配项,则返回其下标。
如果遍历完 haystack 中的所有子字符串,仍然找不到匹配项,则返回 -1。