您的位置:首页 > 其它

28. Implement strStr()

2015-06-06 10:29 357 查看
Implement strStr().

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

Update (2014-11-02):

The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a 
char
*
 or 
String
, please click the reload button  to
reset your code definition.

class Solution {
public:
int strStr(string haystack, string needle) {
int hLen = haystack.length();
int nLen = needle.length();

int i = 0;
int j = 0;
while(i<hLen && j<nLen)
{
if(haystack[i] == needle[j])
{
//如果当前字符匹配成功(即S[i] == P[j]),则i++,j++
++i;
++j;
}
else
{
//如果失配(即S[i]! = P[j]),令i = i - (j - 1),j = 0
//这步是关键,i指向匹配失败的下一个元素
i = i-j+1;
j = 0;
}
}
//匹配成功,返回模式串p在文本串s中的位置,否则返回-1
if(j == nLen)
return i-j;
else
return -1;

}
};

class Solution {
public:
int strStr(char *haystack, char *needle) {

int sLen = strlen(haystack);
int pLen = strlen(needle);

int i = 0;
int j = 0;
while (i < sLen && j < pLen)
{
if (haystack[i] == needle[j])
{
//①如果当前字符匹配成功(即S[i] == P[j]),则i++,j++
i++;
j++;
}
else
{
//②如果失配(即S[i]! = P[j]),令i = i - (j - 1),j = 0
//这步是关键
i = i - j + 1;
j = 0;
}
}
//匹配成功,返回模式串p在文本串s中的位置,否则返回-1
if (j == pLen)
return i - j;
else
return -1;

}

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