leetcode (Implement strStr())

Title:Implement strStr()   28

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/implement-strstr/

 

1. 暴力法

时间复杂度:O(n^2),一次一层while循环,但是变量i是会不断的回溯的,最大是n^2。

空间复杂度:O(1),没有申请额外的空间。

    /**
     * 暴力法
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr(String haystack, String needle) {

        if (needle.length() == 0) {
            return 0;
        }

        if (haystack.length() < needle.length()) {
            return -1;
        }

        int i = 0;
        int j = 0;

        while (i < haystack.length() && j < needle.length()) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            }
            else {
                i = i - j + 1;
                j = 0;
            }
        }

        if (j == needle.length()) {
            return i - j;
        }
        else {
            return -1;
        }

    }

2. KMP法

时间复杂度:O(n^2),一次一层while循环,但是变量i是会不断的回溯的,最大是n^2。

空间复杂度:O(m),申请长度为needle字符串的next数组。

    /**
     * KMP算法:https://www.cnblogs.com/yjiyjige/p/3263858.html
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr1(String haystack, String needle) {

        if (needle.length() == 0) {
            return 0;
        }

        if (haystack.length() < needle.length()) {
            return -1;
        }

        int i = 0;
        int j = 0;
        int next[] = getNext(needle);

        while (i < haystack.length() && j < needle.length()) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            }
            else {
                //i = i - j + 1;
                //j = 0;
                j = next[j];
            }
        }

        if (j == needle.length()) {
            return i - j;
        }
        else {
            return -1;
        }

    }

    /**
     * 求next数组
     * @param needle
     * @return
     */
    private static int[] getNext(String needle) {

        int next[] = new int[needle.length()];
        next[0] = -1;
        int j = 0;
        int k = -1;

        while (j < needle.length() - 1) {
            if (k == -1 || needle.charAt(j) == needle.charAt(k)) {
                next[++j] = ++k;
            }
            else {
                k = next[k];
            }
        }

        return next;

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼王呵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值