7ms recursive Java solution for fun. Without API other than toCharArray()

  • 0

    I was thinking about recursive solution, and feels like it can be simplified to be splicing the haystack to the length of needle, and then compare two arrays of the same length.

    It seems not super elegant for I don't want to use subString() or copy the vals to a new array, but instead keeping a pointer as index for splicing.

    public static boolean charsetEqual(int i, char[] h, char[] n) {
        for (int j = 0; j < n.length; j++) {
            if (h[i + j] != n[j]) return false;
        return true;
    public static int charChar(int i, char[] h, char[] n) {
        if (i > h.length - n.length) return -1;
        else if (charsetEqual(i, h, n)) return i;
        else return charChar(i+1, h, n);
    public static int strStr(String haystack, String needle) {
        char[] h = haystack.toCharArray();
        char[] n = needle.toCharArray();        
        if (n.length == 0) return 0;
        return charChar(0, h, n);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.