文章目录
- 力扣题目
- 代码
力扣题目
给你两个字符串 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;
}