Sunday算法的一种Java实现(Leetcode28. Implement strStr())
来源:互联网 发布:可惜不是你网络短剧 编辑:程序博客网 时间:2024/05/17 09:04
Leetcode第28题Implement strStr()。即寻找目标字符串中模式字符串第一次出现的位置。
这类字符串匹配查找的问题,无外乎KMP,BM,Sunday算法。KMP太烧脑,BM和Sunday算法本质上是一样的,但是Sunday算法更取巧,效率更高(天下间的算法要是都有像Sunday算法那样短小精悍的版本,该多好...)。
具体原理网上各种有。要注意的细节有两个:
(1)当目标串和模式串顺序比对不成功后,开始用目标串中和模式串当前对齐的最后一个字符的下一个字符,来和模式串中的字符一一倒序比对(目标串中这个字符是固定的,模式串会被从尾到头对比),因为顺序比对不成功的话,模式串起码要移动一位(Sunday算法取巧思维无处不在...)。
(2)倒序比对时,遇到模式串中第一个相等的字符,马上停止比对,进行模式串的移位,开始下一次顺序比对。假设此时目标串比对的位置是s1,模式串从前到后能和s1处字符相等的字符位置分别为p1,p2,...,pn,那么sunday算法在遇到pn时就停止倒序比对了,而不是往前再寻找相等的字符位置。有人可能想,为什么不继续倒序往前找,直到找到模式串中最前面相等的字符位置p1,这样模式串的移位更多,效率更高。这样做的问题在于,被跳过的几个移位p2,...,pn,可能存在模式串匹配的情况,而p1及往后位置的目标串中并没有和模式串匹配的子字符串,即便有匹配,题目也是要求第一次出现匹配的位置,所以倒序比对时找到第一个相等的字符就进行移位,达到寻找首次匹配模式串位置的目标。
代码:
public class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null) { return -1; } if (needle.isEmpty()) { return 0; } if (haystack.isEmpty()) { return -1; } char[] srcArr = haystack.toCharArray(); char[] tarArr = needle.toCharArray(); int i = 0, j = 0; while (i + tarArr.length - 1 < srcArr.length) { if (srcArr[i+j] == tarArr[j]) { if (j == tarArr.length - 1) { return i; } j++; continue; } if (i+ tarArr.length == srcArr.length) { return -1; } boolean isMatch = false; for (int k = tarArr.length - 1; k >= 0; k--) { if (srcArr[i + tarArr.length] == tarArr[k]) { isMatch = true; i += tarArr.length - k; j = 0; break; } } if (!isMatch) { i += tarArr.length + 1; j = 0; } } return -1; }}
阅读全文
0 0
- Sunday算法的一种Java实现(Leetcode28. Implement strStr())
- [LeetCode28] Implement strStr()
- Leetcode28 Implement strStr()
- LeetCode28:Implement strStr()
- [LeetCode28] Implement strStr()
- Leetcode28: Implement strStr()
- Leetcode28. Implement strStr()
- leetcode28: Implement strStr()
- leetcode28. Implement strStr()
- leetcode28. Implement strStr()
- LeetCode28. Implement strStr()
- leetcode28 Implement strStr()
- LeetCode28. Implement strStr()
- LeetCode Implement strStr()(Sunday算法)
- LeetCode28——Implement strStr()
- LeetCode: Implement strStr()(字符串匹配:Sunday算法)
- java算法之简单的Implement strStr
- 【LeetCode28】【 Implement strStr()】length,length(),size()
- Best Time to Buy and Sell Stock II
- Ethereum以太网搭建本地开放环境简明教程
- Kafka性能测试方法
- 我的学习之路_第三十三章_会话技术 cookie&session
- AXIS调用jws发布的webservice出现Cannot find dispatch method for
- Sunday算法的一种Java实现(Leetcode28. Implement strStr())
- git sourcetree beyond compare
- jekyll serve 报错/usr/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load
- 2017年7月3号-面试题目整理第一天
- 腾讯js面试题1
- Java中如何实现Web的会话跟踪
- C#反射(Reflection)详解
- busybox命令(不定时更新)
- 菜鸟心历之路(5)