Sharing my easy-understand java solution


  • 3
    B
    public class Solution {
    public int strStr(String haystack, String needle) {
        if (needle=="") return 0;
        int i=0;
        int j=0;
        int k=0;
        while(i<haystack.length() && haystack.length()-i>=needle.length()){
            k=i;
            while(j<needle.length()){
                if(haystack.charAt(k)!=needle.charAt(j)){
                    j=0;
                    break;
                }
                j++;
                k++;
            }
            if(j==needle.length()) return i;
            i++;
        }
        return -1;
    }
    

    }

    i iterates each position in the haystack
    j iterates each position in the needle
    when the haystack matches the needle in one position, match the rest.
    (At first I used indexOf() in java like many others here and it was amazing to see one line of code works. )


  • 0
    Y

    Nice nice nice!


  • 0
    S

    The grader says wrong answer for your solution.


  • 0
    F

    fixed few bugs, but basic same idea.

    public int strStr(String haystack, String needle) {
        
        int h1 = 0;
        int h2 = 0;
        int n1 = 0;
        
        if (needle.length() == 0) return 0;
        if (needle.length() > haystack.length()) return -1;
        
        while (h1 <= haystack.length() - needle.length()) {
            h2 = h1;
            while (n1 < needle.length()) {
                if (haystack.charAt(h2) != needle.charAt(n1) ) {
                    n1 = 0;
                    break;
                }
                h2 += 1;
                n1 += 1;
            }
            if (n1 == needle.length()) return h1;
            h1 += 1;
        }
        return -1;
    }

Log in to reply
 

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