Java solution


  • 0
    L
    public int strStr(String haystack, String needle) {
            if(needle.length() == 0) return 0;
            int index = 0;
            for(int i = 0; i < haystack.length(); i++) {
                if(haystack.charAt(i) == needle.charAt(index)) {
                    index++;
                } else if(index != 0){
                    i = i - index;
                    index = 0;
                }
                if(index == needle.length()) {
                    return i - index + 1;
                }
            }
            return -1;
        }
    

Log in to reply
 

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