LeetCode:Implement strStr()
2016-06-04 20:24
267 查看
Implement strStr()
Total Accepted: 109580 TotalSubmissions: 435297 Difficulty: Easy
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
Hide Tags
Two Pointers String
Hide Similar Problems
(H) Shortest Palindrome
思路:
KMP算法。
c++ code:
class Solution { public: int strStr(string haystack, string needle) { int i = 0; int j = 0; int sLen = haystack.length(); int pLen = needle.length(); int next[pLen]; getNext(needle, next); while (i < sLen && j < pLen) { //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++ if (j == -1 || haystack[i] == needle[j]) { i++; j++; } else { //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j] //next[j]即为j所对应的next值 j = next[j]; } } if (j == pLen) return i - j; else return -1; } void getNext(string p, int next[]) { int pLen = p.length(); int k = -1; int j = 0; next[0] = -1; while (j < pLen) { //p[k]表示前缀,p[j]表示后缀 if (k == -1 || p[k] == p[j]) { k++; j++; next[j] = k; } else { k = next[k]; } } } };
相关文章推荐
- 【杭电】[1863]畅通工程
- 使用nfs服务器将Windows和ubuntu进行文件共享
- clip 用法和兼容性(转载)
- Java序列化
- 有刷电机结构图
- 模拟实现memmove
- CentOS 6.6 下源码编译安装MySQL 5.7.5
- Python--基础学习--流程控制
- 4. 使用别的json解析框架【从零开始学Spring Boot】
- 调用系统下载安装apk
- 56. Merge Intervals
- 手机开发实战61——TCP/IP协议简介
- Android 生成xml文件
- Chrome浏览器导入Burp Suite证书
- IE11无法打开网页,一片空白,Internet选项灰色无法点击的问题
- 个人开发总结(1)-ios创建对象
- CMD命令简单使用
- MFC hook注入dll,远程线程注入dll
- nginx 配置文件解释及优化安全
- JVM 调优和垃圾回收器说明