当前位置:   article > 正文

力扣-28. 找出字符串中第一个匹配项的下标

力扣-28. 找出字符串中第一个匹配项的下标

文章目录

力扣题目

给你两个字符串 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 。

提示:

1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成

代码

思路分析:
1.使用strstr函数先判断是否是字串;
2.利用strstr函数返回值的特性,来判断符合条件首位置的字符;
3.遍历字符串,看位置后边是否是连续的字串。

int strStr(char* haystack, char* needle) 
{
	char *ret = NULL;

	ret = strstr(haystack, needle);/*判断needle是否是haystack的字串*/

	int i = 0, j = 0, z = 0;
	int lenMax = strlen(haystack);
	int lenMin = strlen(needle);
	int count = 0;
	int index = 0;
	if (NULL == ret)/*不是字串返回-1*/
	{
		return -1;
	}
	else
	{
		for (i = 0; i < lenMax; i++)/*遍历haystack字符串*/
		{
            count = 0;/*此处一定要置一下0,防止记录了上一个与起始字符串开头相同的字符*/
			if (haystack[i] == *ret)/*找到与字串第一个字母相同的位置*/
			{
				index = i;/*记录索引位置*/
                /*判断当前位置后边的字符串是否是字串*/
				for (j = i, z = 0; z < lenMin; j++, z++)
				{
					if (haystack[j] == needle[z])
					{
						count++;
					}
					else
					{
						count = 0;
					}
				}

				if (count == lenMin)/*是子串返回当前位置*/
				{
					return index;
				}
			}
			else/*没找到个数变量要置0*/
			{
				count = 0;
			}
		}
	}
    return -1;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/117359
推荐阅读
相关标签
  

闽ICP备14008679号