Why is my kmp code wrong when input ""?


  • 0
    G

    when input is "", the result is wrong.
    Runtime Error Message: Line 20: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    Last executed input: "", ""

    I have already judged it.

    here is the code.

    public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack==null||needle==null||haystack.isEmpty()||needle.isEmpty()||needle.length()>haystack.length())
            return -1;
        int len = needle.length();
    	int[] next = new int[len];
    	next[0] = -1;
    	int j=0,k=-1;
    	while(j<len-1){
    		if(k==-1||needle.charAt(j)==needle.charAt(k)){
    			j++;
    			k++;
    			next[j]=k;
    		}
    		else
    			k=next[k];
    	}
    	j=k=0;
    	while(j<haystack.length()-1){
    		if(k==-1||haystack.charAt(j)==needle.charAt(k)){
    			j++;
    			k++;
    		}
    		else
    			k=next[k]-1;
    		if(k==len)
    			return j-len;
    	}
    	return -1;
    }
    

    }


Log in to reply
 

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