package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/11/7 */ public class NC_142_MAX_DUPSUBSTR { public int solve (String a) { char[] aChar = a.toCharArray(); int tabSize = aChar.length/2; //从最大窗口开始,比较两个窗口字符串数组 for(;tabSize>0;tabSize--){ //窗口可滑动次数为字符串数组长度减去(窗口长度*2),变化项为窗口左侧起始位置,每次滑动一格 for(int tabSlide=0;tabSlide<=aChar.length-tabSize*2;tabSlide++){ int compareSize = 0; //如果两个窗口对应字符串相同,直接返回长度 if(compareTabString(aChar,tabSlide,tabSize)){ return tabSize*2; } } } //没有 return 0; } //比较两个窗口字符串的函数(相同则返回true作为判断重复子串的标准) public boolean compareTabString(char[] a,int tabIndex,int tabSize){ for(int i=tabIndex;i<tabIndex+tabSize;i++){ if(a[i]!=a[i+tabSize]) return false; } return true; } }
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/7/27 */ public class NC_149_KMP { public static int kmp (String mode, String mainString) { // write code here if (mode == null || mode.length() == 0 || mainString == null || mainString.length() == 0){ return 0; } int[] next = getNext3(mode); int sIdx = 0; int tIdx = 0; int m = mode.length(); int n = mainString.length(); int count = 0; while(tIdx < n){ if (sIdx == -1 || mode.charAt(sIdx) == mainString.charAt(tIdx)){ tIdx ++; sIdx ++; }else{ sIdx = next[sIdx]; } if (sIdx == m){ // count += 1; // sIdx = next[sIdx]; //改写下 发现第一个返回下标 return tIdx - m ; } } return count; } public static int kmp2 (String mode, String mainString) { // write code here if (mode == null || mode.length() == 0 || mainString == null || mainString.length() == 0){ return 0; } int[] next = getNext3(mode); int lengM = mainString.length(); int lengthS = mode.length(); int mIndex = 0;//主 int sIndex = 0; while (mIndex < lengM) { if (sIndex == -1 || mainString.charAt(mIndex) == mode.charAt(sIndex)) { sIndex++; mIndex++; } else { sIndex = next[sIndex]; } if (sIndex == lengthS) { return mIndex - lengthS; } } return -1; } private static int[] getNext(String S){ char[] chs = S.toCharArray(); int n = chs.length; int[] nexts = new int[n + 1]; nexts[0] = -1; nexts[1] = 0; int i = 2; int j = 0; while(i <= n) { if (j == -1 || chs[i - 1] == chs[j]){ j++; nexts[i] = j; i++; }else{ j = nexts[j]; } } return nexts; } public static void main (String[] args) { // String s = "ababab"; // String t = "abababab"; String s = "ghxx"; String t = "abbghxxrt"; System.out.println(kmp(s,t)); } public static int[] getNext2(String S) { char[] chs = S.toCharArray(); int length = S.length(); int[] next = new int[length + 1]; int i = 2; int j = 0; next[0] = -1; next[1] = 0; while (i<=length) { if (j == -1 || chs[i-1] == chs[j]) { j++; next[i] = j; i++; } else { j = next[j]; } } return next; } public static int[] getNext3(String str) { char[] chs = str.toCharArray(); int length = str.length(); int[] next = new int[length + 1]; next[0] = -1; next[1] = 0; int i = 2; int j = -1; while (i<=length) { if (j == -1 || chs[i-1] == chs[j]) { j++; next[i] = j; i++; } else { j = next[j]; } } return next; } }