leetcode 28. Implement strStr()
来源:互联网 发布:faded软件下载 编辑:程序博客网 时间:2024/06/14 00:01
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"Output: -1
有两种方法:
1、普通:截取长字符串的部分出来比较。
2、运用KMP算法,两个指针的移动来处理。
KMP算法请点 http://blog.csdn.net/liqinzhe11/article/details/78562256
class Solution {public: int strStr(string hay, string nee) { //way-1 /* if (nee.size() > hay.size()) return -1; if (nee.size() == 0) return 0; for (int i = 0; i <= hay.size() - nee.size(); i++) { if (hay.substr(i, nee.size()) == nee) return i; } return -1; */ //way-2 KMP string t = hay; string p = nee; int i = 0; //主串位置 int j = 0; //模式串位置 vector<int> next(p.size() + 1, -1); buildnext(p, next, p.size()); int tsize = t.size(); //这个地方size()需要转化,不然后面while循环会突然退出 int psize = p.size(); while (i < tsize && j < psize ) { if (j == -1 || t[i] == p[j]) // 当j为-1时,要移动的是i,当然j也要归0 { i++; j++; } else// i不需要回溯了 i = i - j + 1; { j = next[j]; } } if (j == p.size()) return i - j; else return -1; } private: void buildnext(string& s, vector<int>& next, int n) { //next[j]的值(也就是k)表示,当P[j] != T[i]时,j指针的下一步移动位置。 int k = -1; int j = 0; while(j < n) { if(k == -1 || s[j] == s[k]) { next[++j] = ++k; } else { k = next[k]; } } } };
阅读全文
0 0
- [LeetCode]28.Implement strStr()
- LeetCode --- 28. Implement strStr()
- LeetCode 28.Implement strStr()
- [Leetcode] 28. Implement strStr()
- 【leetcode】28. Implement strStr()
- [leetcode] 28.Implement strStr()
- Leetcode-28.Implement strStr()
- 28. Implement strStr() LeetCode
- leetcode 28. Implement strStr()
- [LeetCode]28. Implement strStr()
- leetcode 28. Implement strStr()
- Leetcode 28. Implement strStr()
- leetcode 28.Implement strStr()
- LeetCode *** 28. Implement strStr()
- LeetCode 28. Implement strStr()
- leetcode-28. Implement strStr()
- leetcode 28. Implement strStr()
- leetcode 28. Implement strStr()
- Unity Shader 学习笔记(19) 屏幕后处理效果、调整亮度、饱和度、对比度
- SpringCloud消息总线
- Hibernate的generator属性
- IDEA发布项目 导包出错
- python之_requests库学习_2(post请求参数传递)
- leetcode 28. Implement strStr()
- 解决HotClickView开启移动和缩放后热区与背景bitmap显示错位的问题
- 揭秘入围央采的锐捷大数据安全平台是什么东西?
- 实现图片沿水平和竖直方向翻转(旋转180度)
- pace.js网页自动加载进度条插件-好东西
- js中过滤输入框,和文本域中的特殊字符串。
- shell脚本中判断上一个命令是否执行成功
- 结构体和指针
- mysql编码uft8与gbk的区别