您的位置:首页 > 其它

leetcode 28. Implement strStr()

2017-04-05 17:08 330 查看

[Leetcode 28]  Implement strStr() 子串匹配,返回第一次出现的位置,C语言实现

Description

Implement strStr().

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

int strStr(char* haystack, char* needle) {
int mlength, slength;
int i, j;
int k;
mlength = strlen(haystack);
slength = strlen(needle);
if(mlength == 0 && slength == 0) return 0;//可省略
if(mlength < slength) return -1;
for(i = 0; i <= mlength - slength; i++)
{
k = i;
j = 0;
while(k <= mlength && j < slength && haystack[k] == needle[j])
{
k++;
j++;
}
if(j == slength)
{
if(haystack[k - 1] == needle[j - 1])    return i;//判断最后一个字符是否也匹配
}

}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息