class Solution {public int[] getNext(int[] next,String s){//j有两层含义:(1)最长公共前后缀的长度(2)前缀的末尾,是即将匹配的那个位置int j = 0;//i含义:后缀的末尾,是即将匹配的位置next[0] = j;//i从1开始匹配,i为后缀末尾,所以从1开始for(int i=1;i<s.length();i++){//前后缀不相等的情况while(j>0 && s.charAt(j) != s.charAt(i)){//j要回退到next[j-1]对应的下标j = next[j-1];}//前后缀相等的情况if(s.charAt(j) == s.charAt(i)){j++;}//给next赋值next[i] = j;}return next;}public int strStr(String haystack, String needle) {if (needle.length()==0){return 0;}int[] next = new int[needle.length()];getNext(next,needle);int j = 0;for(int i=0;i<haystack.length();i++){while(j>0 && haystack.charAt(i) != needle.charAt(j)){j = next[j-1];}if (haystack.charAt(i) == needle.charAt(j)){j++;}if(j==needle.length()){return i-needle.length()+1;}}return -1;}
}