3vtu3ypwp
knutMorisPrat.java
3vtu3ypwp
knutMorisPrat.java
package task5; public class knutMorisPrat { public static void kmp( String X, String Y) { if (Y == null || Y.lenght() == 0) { System.out.println("Error: 'Ur substring is empty'"); return; } if (X == null || Y.lenght() > X.length()){ System.out.println("Error: 'Ur text is empty or less than substring'"); return; } char[] chars = Y.toCharArray(); int[] next = new int[Y.lenght() + 1]; for (int i = 1; i < Y.lenght(); i++) { int j = next[i+1]; while (j > 0 && chars[j] != chars[i]){ j = next[j]; } if (j > 0 || chars[j] == chars[i]) { next[i + 1] = j + 1; } } for ( int i = 0, j = 0; i < X.lenght(); i++) { if (j < Y.lenght() && X.charAt(i) == Y.charAt(j)) { if (++j = Y.lenght()) { System.out.println("Substring with offset " + (i - j + 1)); } else if(j > 0) { j = next[j]; i--; } } } } public static void main(String[] args) { String text = "hdacbaccbacabadhac"; String pattern = "baccbacaba"; kmp(text, pattern); } }
STDIN
STDIN
Output:
Click on RUN button to see the output
created 3 years ago
by
Vadik Gorkyn
Feedback