leetcode 28 简单 实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0)
return 0;
int i = 0;
int j = 0;
while(haystack[i] != '\0' && needle[j] != '\0')
{
if(haystack[i] == needle[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == needle.length())
return i - j;
return -1;
}
};
就直接暴力遍历,如果找到了两个字符串都相等的元素,就都加1,如果没找到,那么长的字符串加1,短的就赋值为0。
自己在思考的时候,想的过于简单了