您的位置:首页 > 编程语言 > C语言/C++

LeetCode_Easy心得:28. Implement strStr()(C语言)

2017-08-01 14:20 369 查看
Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

/** 题目分析:本题要求我们在输入字符串haystack[] 中找出第一次出现的子字符串needle[] 是位置。 */

Example:

haystack[] = "1234", needle[] = "34";

return 2;      // 这里的2是指在字符串haystack[] 中出现子字符串needle[] 的起始位置(也就是haystack[2])

/** 代码思路:首先需要三个整数变量 i, j, temp 来表示字符串下表,其中 i遍历输入字符串haystack[], temp表示 i下标的haystack[], j是遍历子字符串needle[]。具体如下图所示:

                                                 


最终目标就是比较 haystack[temp]与 needle[j]各位置是否相等,若相等则返回下标 i,即满足条件的下标位置。 */

int strStr(char haystack[], char needle[]) {
int i, j, temp; // 三个下标;

if(needle[0]=='\0') return 0; // 如果子字符串为空,直接返回0;

for(i=0; haystack[i]; i++){ // 用 i遍历haystack[];
temp = i; // 将 i赋值给临时变量 temp;
j = 0; // j=0, 表示了子字符串从头遍历;

while(needle[j] == haystack[temp] || needle[j] == '\0'){ // needle[j]与 haystack[temp]比较;
if(needle[j] == '\0')
return i; // needle[j] == '\0'说明子字符串比较完成,返回此事下标 i;
else
j++, temp++;// 即needle[j]还没有全部比完,下表继续向后推;
}

}

return -1; // 不存在即 needle[]子字符串,因此返回-1;
}

// LeetCode运行时间:630ms ± 10ms;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: