【LeetCode】 121 實現 strStr()

題目:

image-20210209024303199

這道題力扣和牛客的題目略微不同,所以我以力扣爲準

image-20210209024310916

解題思路:

滑動窗口

image-20210209024324561

https://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"));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章