LeetCode每日一题:implement strstr

问题描述

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

问题分析

这道题考的是KMP算法,但是题目返回值却很诡异,我用indexof返回索引再改成String类型却总是过不了。

代码实现

public String strStr(String haystack, String needle) {
        if (needle.length() == 0) return haystack;
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.length() - i + 1 < needle.length()) return null;
            int k = i;
            int j = 0;
            while (j < needle.length() && k < haystack.length() && needle.charAt(j) == haystack.charAt(k)) {
                j++;
                k++;
                if (j == needle.length()) return haystack.substring(i);
            }
        }
        return null;
    }

你可能感兴趣的:(LeetCode每日一题:implement strstr)