力扣:
实现 strStr() 函数。
题目:
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
输入输出:
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。首先有四种状态,haystack为空,needle不为空;haystack不为空,needle为空;haystack和needle都为空;或者二者都不为空。当needle为空时,不论haystack的长度为多少,直接返回0.
class Solution
{
public:
int strStr(string haystack, string needle)
{
int needle_len = needle.length();//获得两个字符串长度
int hay_len = haystack.length();
if(needle_len==0)
return 0;
for (int i = 0; i <= hay_len - needle_len;)//从下标为0~hay_len-needle_len开始查到匹配字符
{
if (haystack[i] == needle[0] && haystack[i + needle_len - 1] == needle[needle_len - 1])//如果首尾字符都匹配,则比较中间,如果haystack长度比needle小,直接结束循环
{
int first = 0; int flag = 0;
while (first<needle_len-1)
{
if (haystack[i + first] != needle[first])
{
flag = -1;
break;
}
else
first++;
}
if (flag == 0)//完全匹配
return i;
}
i++;
}
return -1;
}
};