leetcode-cn 实现strStr()

题目如图:
实现strStr()
其实这道题至关于让咱们本身手写indexOf(),平时用惯了api,手写起来不是很容易,我本身就换了好几种写法,代码以下:java

private static int strStr(String haystack, String needle) {
            if (haystack == null || needle == null) {
                return -1;
            }
            int needleLength = needle.length();
            if (needleLength == 0) {
                return 0;
            }
            int stackLength = haystack.length();
            if (needleLength > stackLength) {
                return -1;
            }
            int i = 0, j = 0, count = 0;
            // i < stackLength - (needleLength - j - 1) 目的是为了减小查找次数
            // 例如 A = "aabbccdef" B = "def" 当 j = 0 的时候最多只能到A串的'd',后面的“ef”不必查找
            // 当 j = 1 的时候 最多只能到 A 中的 'e' 至关于动态限制
            for (; j < needleLength && i < stackLength - (needleLength - j - 1); i++, j++) {
                while (haystack.charAt(i) != needle.charAt(j) && i < stackLength - (needleLength - j - 1)) {
                    // 所有遍历了还没找到 只针对于 needleLength = 1 或者两个字符串长度相等
                    if (i == stackLength - 1 || needleLength == stackLength) {
                        return -1;
                    }
                    if (count == 0) {
                        // 没有找到过,就一直找下去
                        ++i;
                    } else {
                        // 找到过,可是中间某个不匹配了,要从新找 即 j 指针指向 0
                        // 例如 abccbcdd 和 bcd 以前匹配到 bc count = 2 
                        // 而后 c 和 d 不匹配,因此须要从新匹配,i 从以前的 index 即 (i - count) 再加 1 位出发就好
                        j = 0;
                        i = (i - count) + 1;
                        count = 0;
                    }
                }
                if (++count == needleLength && i < stackLength - (needleLength - j - 1)) {
                    return i - count + 1;
                }
            }
    
            return -1;
        }

看了第一名的代码,愈发以为jdk做者的强大🤣
indexOf()
实现strStr()api

相关文章
相关标签/搜索