[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
原创粉丝点击