Pagini recente » Cod sursa (job #2615467) | Cod sursa (job #1124550) | Cod sursa (job #2839752) | Cod sursa (job #2954331) | Cod sursa (job #1743598)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static long SYMBOLS = 52;
private static long MODULO1 = 1999999973;
private static long MODULO2 = 1999999943;
private static long pow(long x, long power, long MODULO) {
long answer = 1;
while (power-- > 0) {
answer *= x;
answer %= MODULO;
}
return answer;
}
private static long[] hashString(String string, int sequenceLength, long MODULO) {
long[] hashes = new long[string.length() - sequenceLength + 1];
for (int it = 0; it < sequenceLength; ++it) {
hashes[0] = ((SYMBOLS * hashes[0]) % MODULO + string.charAt(it)) % MODULO;
}
long power = pow(SYMBOLS, sequenceLength - 1, MODULO);
for (int it = sequenceLength; it < string.length(); ++it) {
int index = it - sequenceLength;
hashes[index + 1] = (SYMBOLS * (hashes[index] - ((power * string.charAt(index)) % MODULO) + MODULO))
% MODULO;
hashes[index + 1] = (hashes[index + 1] + string.charAt(it)) % MODULO;
}
return hashes;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("strmatch.in"));
BufferedWriter writer = new BufferedWriter(new FileWriter("strmatch.out"));
String pattern = reader.readLine();
String string = reader.readLine();
if (pattern.length() > string.length()) {
writer.write("0");
} else {
long[] hashes1 = hashString(string, pattern.length(), MODULO1);
long[] hashes2 = hashString(string, pattern.length(), MODULO2);
long[] patternHash1 = hashString(pattern, pattern.length(), MODULO1);
long[] patternHash2 = hashString(pattern, pattern.length(), MODULO2);
long matches = 0;
List<Integer> matchesStart = new ArrayList<>();
for (int it = 0; it < hashes1.length; ++it) {
if (hashes1[it] == patternHash1[0] && hashes2[it] == patternHash2[0]) {
++matches;
if (matchesStart.size() < 1000) {
matchesStart.add(it);
}
}
}
writer.write(matches + "\n");
for (Integer it : matchesStart) {
writer.write(it + " ");
}
}
reader.close();
writer.close();
}
}