28. Implement strStr()
来源:互联网 发布:投资组合优化模型 编辑:程序博客网 时间:2024/06/04 01:38
题目:Implement strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
找一个字符串B在另一个字符串A中的起始位置。
需要注意NULL和""的区别。
char *str = NULL //申明字符串指针str并让它指向空地址
char *str = "" //申明字符串指针str并让它指向空字符串
空字符串不是空地址,空地址就是0, 而且空字符串是有地址空间的。
比较笨的办法,就是两次循环,每个位置作为起始位置,开始判断是否相等,如果不相等那么就继续下一个循环,相等就继续比较。
代码:
int strStr(char* haystack, char* needle) { int i=0,j=0; int ret=0; if(!haystack && !needle) return 0; if(!haystack && needle) return -1; if(haystack && !needle) return -1; if(!(*haystack) && !(*needle) ) return 0; if(!(*haystack) && *needle ) return -1; if(*haystack && !(*needle) ) return 0; //printf("The track1,haystack[i] is %c\n",*haystack); while(haystack[i]!='\0') { int tmp=i; int t=i; ret=0; //printf("Before: The haystack[i] is %c, the needle[ret] is %c\n",haystack[i],needle[ret]); while(haystack[t]!=NULL && needle[ret]!=NULL && haystack[t]==needle[ret]) { t++; ret++; continue; } //printf("After: The haystack[i] is %c, the needle[ret] is %c\n",haystack[i],needle[ret]); if(needle[ret]==NULL) { ret=tmp; return ret; } else if(haystack[t]==NULL) { return -1; } else { //printf("The track"); ret=-1; i++; } } return ret; }
0 0
- [LeetCode]28.Implement strStr()
- LeetCode --- 28. Implement strStr()
- LeetCode 28.Implement strStr()
- [Leetcode] 28. Implement strStr()
- 28. Implement strStr()
- 【leetcode】28. Implement strStr()
- [leetcode] 28.Implement strStr()
- Leetcode-28.Implement strStr()
- 28. Implement strStr()
- 28. Implement strStr()
- 28. Implement strStr()
- 28. Implement strStr() LeetCode
- 28. Implement strStr()
- leetcode 28. Implement strStr()
- [LeetCode]28. Implement strStr()
- 28. Implement strStr()
- 28. Implement strStr()
- 28. Implement strStr()
- EditText的部分操作
- 内网一键生成 LetsEncrypt HTTPS证书 - 3 - 生成证书
- C++11语言可用性的强化
- 自定义控件无法直接添加到axml解决方法
- redis的消息队列
- 28. Implement strStr()
- C#——多态
- C#中Regex类用法
- mysql命令
- Error(408) hv01.cloud.cn has an unsupported version of the Virtual Machine Manager agent installd
- cssText实现js添加样式
- redis删除指定开头的键值数据(命令行)
- 帝国cms制作手机wap站完美教程
- 注册码系统防破解教程,如何防破解?