【leetcode KMP算法实现】Implement strStr()
2014-08-31 21:51
465 查看
题目:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解析:实现strStr()方法,给定字符串haystack和needle,返回在haystack中第一次出现needle的位置。该题的一般解法非常简单,将haystack中的每个字符开头的子串和needle进行比对,如果相等即返回该字符开头的子串。该算法的时间复杂度为O(m*n),m为haystack的长度,n为needle的长度。
我用KMP算法实现该字符串比对问题,首先针对模式串needle求出它的next数组,然后再遍历haystack字符串。
Java AC代码如下:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解析:实现strStr()方法,给定字符串haystack和needle,返回在haystack中第一次出现needle的位置。该题的一般解法非常简单,将haystack中的每个字符开头的子串和needle进行比对,如果相等即返回该字符开头的子串。该算法的时间复杂度为O(m*n),m为haystack的长度,n为needle的长度。
我用KMP算法实现该字符串比对问题,首先针对模式串needle求出它的next数组,然后再遍历haystack字符串。
Java AC代码如下:
public class Solution { public String strStr(String haystack, String needle) { if (haystack == null || needle == null) { return null; } int[] next = getNext(needle); int pS = 0, pH = pS, pN = 0; while (pS + needle.length() <= haystack.length()) { if (pN == needle.length()) { return haystack.substring(pS); } else if (haystack.charAt(pS + pH) == needle.charAt(pN)) { pH++; pN++; } else if (next[pN + 1] == 0) { pH = pN = 0; pS++; } else { pH -= (pN - next[pN]); pS += (pN - next[pN]); pN = next[pN]; } } return null; } public static int[] getNext(String needle) { int[] next = new int[needle.length() + 1]; next[0] = -1; needle = '$' + needle; for (int i = 1; i < needle.length(); i++) { if (next[i - 1] == 0) { next[i] = needle.charAt(i) == needle.charAt(1) ? 1 : 0; } else { int before = next[i - 1]; while (before != -1) { if (needle.charAt(before + 1) == needle.charAt(i)) { next[i] = before + 1; break; } else { before = next[before]; } } } } return next; } }
相关文章推荐
- leetcode 题解 || Implement strStr() 问题 (即 KMP 算法实现)
- LeetCode_28---Implement strStr() [KMP算法,字符匹配算法]
- [Leetcode][python]Implement strStr()/KMP算法
- [LeetCode] Implement strStr() 实现strStr()
- LeetCode Implement strStr() 实现strstr()
- Leetcode 28 Implement strStr() KMP算法
- LeetCode专题-Python实现之第28题: Implement strStr()
- LeetCode 28 Implement strStr() (实现找子串函数)
- [C++]LeetCode 28: Implement strStr() (实现strStr()函数)
- leetcode5 Implement strstr() 实现strstr函数功能
- leetcode | Implement strStr() | 实现字符串查找函数
- 每天一道LeetCode-----KMP算法查找子串,重新实现strStr()函数
- [Leetcode] Implement strStr()与 KMP算法
- LeetCode 之 Implement strStr() — C 实现
- LeetCode 28 Implement strStr()(实现strStr()函数)
- 【LeetCode】005 Implement strStr() 函数strStr()的功能实现
- LeetCode.28 Implement strStr() (KMP算法实现子串匹配)
- Implement strStr() 实现strStr函数 @ LeetCode
- leetcode——Implement strStr() 实现字符串匹配函数(AC)
- leetcode 28: Implement strStr() (KMP算法)