My 2ms Java solution


  • 0
    X
    public class Solution{
    public int strStr(String haystack, String needle){
        if(needle.length()==0)return 0;
        if(haystack.length()==0) return -1;
        for(int i = 0, d = 1; i + needle.length() <= haystack.length(); i += d == 1 ? 1 : d - 1){
            d = 1;
            if(haystack.charAt(i) != needle.charAt(0) 
                || haystack.charAt(i + needle.length() - 1) != needle.charAt(needle.length() - 1))
                continue;
            for(int j = 0; ; j++){
                if(j == needle.length()) return i;
                if(i + j == haystack.length()) return -1;
                d = d == 1 && j > 0 && haystack.charAt(j) == needle.charAt(0) ? j : d;
                if(needle.charAt(j) != haystack.charAt(i + j)) break;
            }
        }
        return -1;
    }
    

    }


Log in to reply
 

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