Java solution 12ms. This question is not easy.


  • 0
    F
    public class Solution {
        public int strStr(String haystack, String needle) {
            int nl = needle.length(), hl = haystack.length(), i=0, j = 0;
            if(nl == 0)
                return 0;
            if(hl < nl)
                return -1;
            while(i<nl&&j<hl-nl+1){
                if(needle.charAt(i)!=haystack.charAt(j+i)){
                    j++;i=0;
                }
                else if (needle.charAt(i)==haystack.charAt(j+i))
                    i++;
            }
            if(i==nl)
                return j;
            else 
                return -1;
            }
        }

Log in to reply
 

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