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
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;
}
};
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; } };
相关文章推荐
- 2015/6/5 杭州--米趣
- 在mysql中统计每人每天num总和
- 小型电子商务网站设计原则
- 修改页面JS 360浏览器
- Base关键字,指定调用基类中的哪个构造函数
- Android广播接收机制详细介绍(附短信接收实现)
- MyEclipse 2015优化七步法<亲测有效>
- 大型电子商务网站架构
- Activity的生命周期
- PHP学习之[第01讲]开启PHP学习之路,融入新互联网时代
- Could not create the view: An unexpected exception was thrown. Myeclipse空间报错
- mysql的常用语句
- UItableView详解--1
- 修改Visual Studio Express 2012新建C++文件编码
- 一起talk C栗子吧(第七回:C语言实例--进制转换)
- JAVA
- 堆栈以及程序变量的存储
- 关于Apache/Tomcat/JBOSS/Neginx/lighttpd/Jetty等一些常见服务器的区别比较和理解
- notepad Function list 插件下载
- 常见Oracle HINT的用法