2
头图

Implement strStr()

Title description: Implement the strStr() function.

Given two strings haystack and needle, please find the first position of needle string in the haystack string (the subscript starts from 0). If it does not exist, -1 is returned.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/implement-strstr/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Exhaustive method
  • First, if needle is empty, return 0 directly; if haystack is empty or the length of haystack is less than the length of needle, return -1 directly;
  • Otherwise, start from the first position of the haystack to match the needle. If it does not match, then continue to traverse the haystack until the traversal is completed, and the result can be obtained.

Description: This method is relatively inefficient.

Solution 2: KMP algorithm
First, construct a next array, first calculate the position of the next jump, and then traverse to match the original string with the matched string according to the position of the next array.
import com.google.common.base.Strings;

public class LeetCode_028 {
    /**
     * 穷举法
     *
     * @param haystack
     * @param needle
     * @return
     */
    public static int strStr(String haystack, String needle) {
        if (needle == null || needle.length() == 0) {
            return 0;
        }
        if (haystack == null || haystack.length() == 0 || haystack.length() < needle.length()) {
            return -1;
        }
        int first = 0;
        while (first < haystack.length()) {
            int matchCount = 0;
            for (int i = 0; i < needle.length() && (i + first) < haystack.length(); i++) {
                if (needle.charAt(i) == haystack.charAt(i + first)) {
                    matchCount++;
                } else {
                    break;
                }
            }
            if (matchCount == needle.length()) {
                return first;
            } else {
                first++;
            }
        }
        return -1;
    }

    /**
     * KMP算法
     *
     * @param haystack 原串
     * @param needle   匹配串
     * @return
     */
    public static int strStr2(String haystack, String needle) {
        if (Strings.isNullOrEmpty(needle)) {
            return 0;
        }
        // 分别获取原串和匹配串的长度
        int haystackLength = haystack.length(), needleLength = needle.length();
        // 原串和匹配串前面都加一个空格,使其下标从1开始
        haystack = " " + haystack;
        needle = " " + needle;

        char[] haystackList = haystack.toCharArray();
        char[] needleList = needle.toCharArray();

        // 构建 next 数组,数组长度为匹配串的长度(next 数组是和匹配串相关的)
        int[] next = new int[needleLength + 1];
        // 构造过程 i = 2, j = 0 开始,i 小于等于匹配串长度【构造 i 从 2 开始】
        for (int i = 2, j = 0; i <= needleLength; i++) {
            // 匹配不成功的话,j = next[j]
            while (j > 0 && needleList[i] != needleList[j + 1]) {
                j = next[j];
            }
            // 匹配成功的话,先让 j++
            if (needleList[i] == needleList[j + 1]) {
                j++;
            }
            // 更新 next[i],结束本次循环, i++
            next[i] = j;
        }

        // 匹配过程,i = 1, j = 0 开始,i 小于等于原串长度【匹配 i 从 1 开始】
        for (int i = 1, j = 0; i <= haystackLength; i++) {
            // 匹配不成功 j = next[j]
            while (j > 0 && haystackList[i] != needleList[j + 1]) {
                j = next[j];
            }
            // 匹配成功的话,先让 j++,结束本次循环后 i++
            if (haystackList[i] == needleList[j + 1]) {
                j++;
            }
            // 整一段都匹配成功,直接返回下标
            if (j == needleLength) {
                return i - needleLength;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        System.out.println(strStr("mississippi", "issi"));

        System.out.println(strStr2("mississippi", "issi"));
    }
}
[Daily Message] In the most beautiful years, do what you like most, don't let down the good times, take the hand of time, warm a place with flowers, take a sunny sky, and embrace your dreams.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!