博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Implement strStr()
阅读量:4640 次
发布时间:2019-06-09

本文共 1804 字,大约阅读时间需要 6 分钟。

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

New version: 4ms

1 class Solution { 2 public: 3     int strStr(string haystack, string needle) { 4         int result = 0; 5         int lenN = needle.size(), lenH = haystack.size(); 6         if(lenN == 0 && lenH == 0) return 0; 7         if(lenN == 0) return 0; 8         if(lenH < lenN) return -1; 9         10         for(int i = 0; i <= lenH - lenN; i++){11             if(haystack[i] == needle[0]){12                 int index = 0, move = i;13                 while(move < lenH && index < lenN && haystack[move] == needle[index]){14                     move++;15                     index++;16                 }17                 if(index == lenN) return i;18             }19         }20         return -1;21     }22 };

 

Analyse: Pay special attention to when the length of haystack is less  than that of needle, and the case that needle is empty.

1 class Solution { 2 public: 3     int strStr(string haystack, string needle){ 4         int index = -1; 5         if(haystack.length() < needle.length()) return index; 6         else if(needle.length() == 0) return 0; 7          8         for(int j = 0; j <= haystack.length() - needle.length(); j++){ 9             int index_needle = 0;10             if(haystack[j] == needle[index_needle]){11                 index = j;12                 for(int k = 1; k < needle.length(); k++){13                     if(haystack[j+k] != needle[index_needle+k]){14                         index = -1;15                         break;16                     }17                 }18             }19             if(index >= 0) return index;20         }21         return index;22     }23 };

转载于:https://www.cnblogs.com/amazingzoe/p/4439241.html

你可能感兴趣的文章
linux下find命令使用举例、
查看>>
GET请求在Tomcat中的传递及URI传递
查看>>
ubuntun 服务器与Mac
查看>>
重温JSP学习笔记--与日期数字格式化有关的jstl标签库
查看>>
java-Date-DateFormat-Calendar
查看>>
封装CLLocationManager定位获取经纬度
查看>>
我的第一篇博客-(Eclipse中或Myeclipse中如果不小心删除了包那可怎么办?)
查看>>
对easyui datagrid组件的一个小改进
查看>>
类似以下三图竞争关系的IT企业
查看>>
Qt5启动画面
查看>>
清明节
查看>>
谈谈一些有趣的CSS题目(七)-- 消失的边界线问题
查看>>
ubuntu如何安装svn客户端?
查看>>
arcgis for javascript (3.17)
查看>>
【MySQL】Win7下修改MySQL5.5默认编码格式
查看>>
AI之路,第二篇:python数学知识2
查看>>
windows10关闭更新,windowsUpdate禁用无效 windows无限重启 一分钟无限重启 win10无法连接到SENS服务...
查看>>
[LeetCode] Alien Dictionary
查看>>
[LintCode] 空格替换
查看>>
JSSDK微信支付封装的支付类方法,代码比较齐全,适合收藏
查看>>