【LeetCode】005 Implement strStr() 函数strStr()的功能实现
来源:互联网 发布:mac 大写键切换输入法 编辑:程序博客网 时间:2024/05/19 12:17
【题目】
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
编写一个函数完成strStr(str1,str2)的功能,即判断字符串str2是否是str1的子串,如果是则该函数返回str2在str1中首次出现的序号;否则,返回-1。
【解析】
进行两层循环,依次比较haystack中的每个元素,若与needle中的第一个元素相同,则比较下一个是否相同,若相同则继续,直到needle检索完毕,return i;。若不遇到不相同,则跳出第二层循环,开始检索haystack中的第二元素。
【程序】
int strStr(char* haystack, char* needle) {
int haylen = strlen(haystack);
int needlen = strlen(needle);
if(haylen < needlen)
return -1;
for(int i = 0; i
for(int j = 0; j
if(needle[j]=='\0') return i;
if(haystack[i+j]!=needle[j]) break;
}
}
return -1;
}
【关于bug】
思路很简单,本不应花费太多时间。卡bug卡了很久,加上网站调试功能不是很强,对于基础较弱的我来说,一遍写对也不容易。找了很久的语法错误之后终于accepted。
bug1: for循环少了花括号结尾。。。
bug2: if判断语句用了赋值符号=。。。
bug3: 跳出循环条件问题。这个详细说明一下。
strlen()函数可以计算字符串的长度,除去最后的'\0'。例如:strlen("abc")的值为3。
若字符串str1的长度为3,则存储空间内的情况是这样:
在for循环中,令初始i=0,跳出循环条件应为i,即i<4,如此才能检索到最后一位空字符。
因此,在使用strlen()作为跳出循环条件时,应当注意最后一位'\0'是否需要。
- 【LeetCode】005 Implement strStr() 函数strStr()的功能实现
- Implement strStr() 实现strStr函数 @ LeetCode
- leetcode 28. Implement strStr() 实现strStr()函数
- [C++]LeetCode 28: Implement strStr() (实现strStr()函数)
- LeetCode 28 Implement strStr()(实现strStr()函数)
- leetcode | Implement strStr() | 实现字符串查找函数
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- Implement strStr() strncmp实现strstr()
- Leetcode刷题记——28. Implement strStr(实现strStr)
- Leetcode#28. Implement strStr()(String find()函数的用法)
- LeetCode: Implement strStr()
- [Leetcode] Implement strstr()
- Leetcode: Implement strStr
- [Leetcode] Implement strStr()
- LeetCode Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- [LeetCode] Implement strStr()
- nil, Nil, NULL, NSNull
- 人体器官探秘-肝脏(生理结构、功能篇)
- Android activity的4种启动模式,launchMode,图文详解
- 输入一个字符串将大写改成小写,小写 改成大写
- 笔记:基金申请注意事项
- 【LeetCode】005 Implement strStr() 函数strStr()的功能实现
- static关键字
- spring学习小结8-使用factoryBean来配置bean
- Delphi创建WebService部署到Apache
- 《THINKING IN JAVA》随笔
- 【LeetCode】006 Bitwise AND of Numbers Range 区间内整数按位与
- java中length属性、length()方法、size()方法的区别
- 对avalon进行精简改造
- windows下Gulp入门详细教程