【LeetCode】 121 实现 strStr()

语言: CN / TW / HK

题目:

image-20210209024303199

这道题力扣和牛客的题目略微不同,所以我以力扣为准

image-20210209024310916

解题思路:

滑动窗口

image-20210209024324561

http://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/

代码:

public class LC122 {
    public int strStr(String haystack, String needle) {
        int L = needle.length(), n = haystack.length();

        for (int start = 0; start < n - L + 1; ++start) {
            if (haystack.substring(start, start + L).equals(needle)) {
                return start;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        LC122 lc122 = new LC122();
        System.out.println(lc122.strStr("noddle", "ddle"));
    }
}