版权声明:本文为博主原创文章,转载请注明出处-- https://blog.csdn.net/qq_38790716/article/details/89761581
实现 函数。
给定一个 字符串和一个 字符串,在 字符串中找出 字符串出现的第一个位置 (从 开始)。如果不存在,则返回 。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
思路:
1)从 中某个字符开始匹配,当与 完全匹配时,返回 字符下标;如果某个字符与 内字符不匹配,则 ;如遍历完 仍未找到则返回
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle == "")
return 0;
if (haystack.size() < needle.size())
return -1;
for (int i = 0; i < haystack.size(); ++i)
{
int j = 0;
for ( j = 0; j < needle.size(); ++j)
{
if (haystack[i + j] != needle[j])
break;
}
if (j == needle.size())
return i;
}
return -1;
}
};
2)调用函数 截取字符串进行匹配。以 中某个字符开始,截取长度等于 长的字符串与 进行匹配,若匹配返回下标
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty())
return 0;
int m = needle.size();
int n = haystack.size();
for (int i = 0; i < n - m + 1; ++i) {
if (haystack.substr(i, m) == needle)
return i;
}
return -1;
}
};