【LeetCode】实现 strStr() | 刷题打卡

302 阅读1分钟

掘金团队号上线,助你 Offer 临门! 点击 查看详情

题目描述

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

示例 1:

输入:haystack = "hello", needle = "ll"
输出:2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr

思路分析

  • 在字符串考察题目中,实现字符串查找是很常见的题目,需要熟练掌握。
  • 整体思路是遍历查找匹配。观察分析暴力法,发现有很多的重复计算。我们可以使用 KMP 算法来减少重复计算,提升查找效率。

代码

public class DayCode {
    public static void main(String[] args) {
        String haystack = "hello", needle = "ll";

        int ans = new DayCode().strStr(haystack, needle);
        System.out.println("ans is " + ans);

        int ans1 = new DayCode().strStr1(haystack, needle);
        System.out.println("ans is " + ans1);

        int ans2 = new DayCode().strStr2(haystack, needle);
        System.out.println("ans is " + ans2);
    }

    /**
     * 时间复杂度 O(m * n)
     * 空间复杂度 O(1)
     *
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        for (int start = 0; start + m <= n; start++) {
            if (haystack.substring(start, start + m).equals(needle)) {
                return start;
            }
        }
        return -1;
    }

    /**
     * 时间复杂度 O(m * n)
     * 空间复杂度 O(1)
     *
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr1(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        for (int i = 0; i + m <= n; i++) {
            boolean flag = true;
            for (int j = 0; j < m; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 时间复杂度 O(m + n)
     * 空间复杂度 O(1)
     *
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr2(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        if (m == 0) {
            return 0;
        }

        int[] pi = new int[m];
        for (int i = 1, j = 0; i < m; i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = pi[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            pi[i] = j;
        }

        for (int i = 0, j = 0; i < n; i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = pi[j - 1];
            }

            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }

            if (j == m) {
                return i - m + 1;
            }
        }

        return -1;
    }


}

总结

  • 在实际的计算中,避免重复计算可以大大提升算法的执行效率。
  • 坚持每日一题,加油!