[LeetCode]28. Implement strStr()
来源:互联网 发布:喀什大清银币 知多少 编辑:程序博客网 时间:2024/05/16 08:27
https://leetcode.com/problems/implement-strstr/
显然本题有解KMP,但是你要从暴力算法开始讲啊!!说不定问的就是暴力算法呢?
解法一:KMP
之前一直不理解,之后看了两个文章就很通俗了,分两步:1、预处理要匹配字符串得到next数组,next之中保存长度为i的字符串与开头字符串匹配的最大长度;2、匹配字符串
讲KMP算法
讲next数组
这个next数组的理解有个神图,这里面A1=A2,B1=B2=B3,这也是为什么如果j、k位置字符不相等j = next[j]的原因
public class Solution { public int strStr(String haystack, String needle) { if (needle.equals("")) { return 0; } int[] next = getNext(needle); for (int i = 0, j = 0; i < haystack.length(); i++) { while (j > 0 && haystack.charAt(i) != needle.charAt(j)) { j = next[j]; } if (haystack.charAt(i) == needle.charAt(j)) { j++; } if (j == needle.length()) { return i - j + 1; } } return -1; } private int[] getNext(String key) { int len = key.length(); // 保存长度为i的前缀最长匹配 int[] next = new int[len + 1]; for (int i = 1, j = 0; i < len; i++) { while (j > 0 && key.charAt(i) != key.charAt(j)) { j = next[j]; } if (key.charAt(i) == key.charAt(j)) { j++; } next[i + 1] = j; } return next; }}
解法二:暴力解,剪枝当前haystack已经匹配到末尾且无正确返回,则此时返回-1.
public class Solution { public int strStr(String haystack, String needle) { for (int i = 0;; i++) { for (int j = 0;; j++) { if (j == needle.length()) { return i; } if (i + j == haystack.length()) { return -1; } if (haystack.charAt(i + j) != needle.charAt(j)) { break; } } } }}
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()
- 鼠标移动到某文字上然后显示图片
- Android Studio 集成simpleUML插件画类图
- 探索网络
- Android Glide You cannot start a load for a destroyed activity 的异常及解决方法
- 读取项目属性文件的几种方式
- [LeetCode]28. Implement strStr()
- 米斯特白帽培训讲义 工具篇 Nmap
- plsql developer 数据库连接:找不到监听器(no listener)
- 创客筑梦,第二届机智云智能硬件36小时开发大赛圆满落幕
- jsp中实现中文简繁体切换
- 51nod 1091 线段的重叠
- 质数因子
- shell下使用mailx发送邮件
- abstract类和abstract方法