Implement strStr()

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

public class Solution {
	private static int[] nextval;
	private static void get_nextval(String needle) {
		nextval = new int[needle.length()+1];
		int i = 0;
		int j = -1;
		nextval[0] = -1;
		while (i < needle.length()-1) {
			if (j==-1 || needle.charAt(i)==needle.charAt(j)) {
				i++;
				j++;
				if (needle.charAt(i)==needle.charAt(j)) {
					nextval[i] = nextval[j];
				} else {
					nextval[i] = j;
				}
			} else {
				j = nextval[j];
			}
		}
	}
    public static int strStr(String haystack, String needle) {
    	get_nextval(needle);
        int i = 0;
        int j = 0;
        while (i<haystack.length() && j<needle.length()) {
        	if (j==-1 || haystack.charAt(i)==needle.charAt(j)) {
        		i++;
        		j++;
        	} else {
        		j = nextval[j];
        	}
        }
        if (j >= needle.length()) {
        	return i-needle.length();
        } else {
        	return -1;
        }
    }
}

 

你可能感兴趣的:(imp)