28.LeetCode Implement strStr()(meidum)[字符串 子串匹配]
2016-04-15 09:56
423 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
strStr(str1,str2)的功能是判断str2是否是str1的子串,解题思路如下:首先判断str2是否是空串,空串是任何字符串的子串返回0;当str2的长度大于str1的时候,那么str2肯定不是str1的子串,返回-1;str2从开始字串针对str1开始扫描,但是由于后面的子串需要完全匹配,所以对str1的扫描只需要扫描到<=str1.size()-str2.size()的地方为止。
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
strStr(str1,str2)的功能是判断str2是否是str1的子串,解题思路如下:首先判断str2是否是空串,空串是任何字符串的子串返回0;当str2的长度大于str1的时候,那么str2肯定不是str1的子串,返回-1;str2从开始字串针对str1开始扫描,但是由于后面的子串需要完全匹配,所以对str1的扫描只需要扫描到<=str1.size()-str2.size()的地方为止。
class Solution { public: int strStr(string haystack, string needle) { if(needle.size()>haystack.size()) return -1; if(needle.size() == 0) return 0; int pos = -1; int i = 0; for(int j=0;j<=haystack.size()-needle.size();j++) { if(haystack[j] == needle[i]) { int p = i,q = j; while(p<needle.size()&&q<haystack.size()) { if(needle[p]!= haystack[q]) break; else { ++p;++q; } } //cout<<p<<endl; if(p == needle.size()) { pos = j; break; } } } return pos; } };
相关文章推荐
- 镜面高光
- 发送POST请求数据包&解决发过去的中文在后台显示乱码"????"
- js当前时间加减一天,和格式化时间格式
- Linux中常用操作命令
- sizeof与strlen的区别:面试回答
- js 合并表格
- Python的网页下载器:urllib2.urlopen
- BFS与DFS
- 光照漫反射(平行光)
- MAC系统显示隐藏文件
- 点光源
- Android Studio:Gradle project refresh failed. Connection timed out: connect.
- Data Guard配置
- java中的变量
- 导出Excel
- resizableImageWithCapInsets 图片拉伸
- Awk使用案例总结(运维必会)
- HTML5的新特性
- C# 模拟光照运算以及背面剔除
- 解决Android 6.0动态添加权限问题