Skip to content

Instantly share code, notes, and snippets.

@NargiT
Created February 6, 2018 21:29
Show Gist options
  • Save NargiT/a33cd578a140611b791a728762e44dc4 to your computer and use it in GitHub Desktop.
Save NargiT/a33cd578a140611b791a728762e44dc4 to your computer and use it in GitHub Desktop.
Repetition
package fr.nargit.repetition;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
BufferedReader in;
String text;
String result;
Map<String, Integer> counts = new HashMap<>();
try {
in = new BufferedReader(new FileReader(new File(args[0])));
text = in.readLine();
//text = "If you rererererepeat a lieieieieieie often enough, it becomes politics.";
final String[] split = text.split(" ");
String token;
for (int j = 0; j < split.length; j++) {
String word = split[j];
for (int i = 2; i < word.length(); i++) {
for (int k = 0; k < word.length() - i; k++) {
token = word.substring(k, k + i);
if (token.length() != token.chars().distinct().count()) {
break;
}
Matcher matcher = Pattern.compile(token).matcher(text);
int count = 0;
String aggregatedToken = token;
while (matcher.find()) {
count++;
aggregatedToken += token;
matcher = Pattern.compile(aggregatedToken).matcher(text);
}
final String key = aggregatedToken.substring(0, count * token.length());
if (count > 1 && !counts.containsKey(key) ||
counts.containsKey(key) && counts.get(key) < count) {
counts.put(key, count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
result = counts.entrySet().stream().max((o1, o2) -> {
if (o1.getKey().length() > o2.getKey().length()) {
return 1;
} else {
return -1;
}
}).get().getKey();
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment