My java solution - violentMatch


  • 0
    S

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


Log in to reply
 

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