import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Stringologia {
public static void najdiVyskyty(String retazec, String vzorka) {
int poz = 0;
while (poz <= retazec.length() - vzorka.length()) {
int i = 0;
while (vzorka.charAt(i) == retazec.charAt(poz + i)) {
if (i == vzorka.length() - 1) {
System.out.println(poz);
break;
}
i++;
}
poz++;
}
}
public static int prefixovySufix(String s) {
for (int poz = 1; poz < s.length(); poz++) {
if (s.charAt(poz) == s.charAt(0)) {
int i = 0;
while(s.charAt(i) == s.charAt(poz + i)){
if (poz + i == s.length() - 1) {
return i + 1;
}
i++;
}
}
}
return 0;
}
private static Map<Character, int[]> kmpTabulka(String s) {
Map<Character, int[]> kmp = new HashMap<Character, int[]>();
for (int i = 0; i < s.length(); i++) {
if (!kmp.containsKey(s.charAt(i))) {
kmp.put(s.charAt(i), new int[s.length()]);
}
}
kmp.put('#', new int[s.length()]);
for (char c : kmp.keySet()) {
int[] r = kmp.get(c);
for (int i = 0; i < r.length; i++) {
if (c == s.charAt(i)) {
r[i] = 0;
} else {
r[i] = i + 1 - prefixovySufix(s.substring(0, i) + c);
}
}
}
return kmp;
}
private static int vratPosun(Map<Character, int[]> kmpTabulka, char c, int i) {
if (!kmpTabulka.containsKey(c)) {
c = '#';
}
return kmpTabulka.get(c)[i];
}
private static int kmpVyskyt(String text, String vzorka) {
Map<Character, int[]> kmpTabulka = kmpTabulka(vzorka);
int poz = 0;
int i = 0;
while(poz <= text.length() - vzorka.length()) {
if (i == vzorka.length()) {
return poz;
}
int d = vratPosun(kmpTabulka, text.charAt(poz + i), i);
poz = poz + d;
i = i + 1 - d;
}
return -1;
}
public static void main(String[] args) {
najdiVyskyty("mama ma emu", "ma");
System.out.println(prefixovySufix("abadaba"));
Map<Character, int[]> kmpTabulka = kmpTabulka("XYXYZ");
for (char c : kmpTabulka.keySet()) {
System.out.println(c + " " + Arrays.toString(kmpTabulka.get(c)));
}
System.out.println(kmpVyskyt("WXYXYXYZ", "XYXYZ"));
}
}