implement strStr()
来源:互联网 发布:linq 更新数据 编辑:程序博客网 时间:2024/06/08 03:57
c语言暴力破解:
int strStr(char* haystack, char* needle){ int i=0,j=0; for( i=0;haystack[i]!='\0';++i) { int t=i; //记录下i的位置 for( j=0;needle[j]!='\0';++j) { if (haystack[i] != needle[j]) { //一旦发现有不相等的,循环停止 break; } else //若相等,则将i加1。j的值在for语句中加1 ++i; } i=t; //循环结束之后,将i的值恢复 if (needle[j] == '\0' )//若循环结束之后,needle[j]的值为'\0' { //子串与主串相匹配,返回i即可 return i; } //若needle[j]不等'\0',则i进行下一次循环 } if (i==0 && needle[0]=='\0') //如果都为空串,代表根本就没有进入循环 return 0; return -1;}
看见大神写的,理解了,又敲了一遍。
这int strStr(char *haystack,char *needle){ if (*needle == '\0') //子串为0,即空串,无论主串是什么,则都存在 return 0; //则返回0 if (*haystack=='\0' || strlen(haystack)<strlen(needle) )//主串为0 return -1; //或者子串长度大于主串长度,则都说明在主串中不存在子串,则返回-1 char* ph=haystack; //pn,ph的值在整个程序运行期间都没有改变 char* pn=needle; //故起记录的作用,记录起始地址 while ( *haystack !='\0' && *needle!='\0')//haystack和needle没有到达文件末尾就循环 { if ( *haystack==*needle) { //若haystack和needle位置上的值相等,则继续haystack和needle下一个位置的元素 ++haystack; //故将haystack和needle加1 ++needle; }//若*haystack和*needle不相等,则比较pn和needle,pn的值为初始地址 else if(pn==needle) //若needle等于初始地址(pn),又needle(子串第一个值)和当前haystack的值 { //不相等 ++haystack;//则将haystack加1,以便继续和子串的第一个的值比较 } else //如果以上两种情况都不满足,则是比较了子串的前(needle-pn)个元素,并且这些元素相等 { //在needle-pn+1个元素的时候不匹配,则需要回溯 haystack=haystack-(needle-pn)+1; //haystack回溯到haystack-(needle-pn)+1 needle=pn; //needle回溯到起始位置 } } if( *needle == '\0' ) //说明找到来 return haystack-ph-(needle-pn); return -1;}
运行时间相差很多,但我感觉处理过程相似,不知道为什么时间相差这么多,欢迎各位指点!
阅读全文
0 0
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- Implement strStr()
- 《剑指offer》求二叉树的最小深度(非递归法)
- Windows路由表配置:双网卡同时上公司内外网
- 斐波拉契数列矩阵连乘(模板)
- ViewGroup的TouchEvent的处理机制
- org.apache.commons.lang.builder.ReflectionToStringBuilder类,用于将对象转换成字符串
- implement strStr()
- 我要通过
- windows环境下ElasticSearch5以上版本安装head插件
- 01. 选择、插入、冒泡排序
- nginx启动与配置
- 2017年-年中总结
- 杨澜:人工智能是镜子,反映欲望、人性和爱【智库2861】
- MFC中GDI超过9999导致程序崩溃问题的解决
- 路由生产算法调研