Я пытаюсь найти шаблоны, которые:
- происходит более одного раза
- длиной более 1 символа
- не являются подстроками любого другого известного шаблона
не зная ни одного из шаблонов, которые могут возникнуть.
Например:
- Строка "мальчик упала на звонок" вернет
'ell', 'the b', 'y '
. - Строка "мальчик упал у колокола, мальчик упал на звонок" вернул
'the boy fell by the bell'
.
Использование двойных for-loops, это может быть грубо принудительно очень неэффективно:
ArrayList<String> patternsList = new ArrayList<>();
int length = string.length();
for (int i = 0; i < length; i++) {
int limit = (length - i) / 2;
for (int j = limit; j >= 1; j--) {
int candidateEndIndex = i + j;
String candidate = string.substring(i, candidateEndIndex);
if(candidate.length() <= 1) {
continue;
}
if (string.substring(candidateEndIndex).contains(candidate)) {
boolean notASubpattern = true;
for (String pattern : patternsList) {
if (pattern.contains(candidate)) {
notASubpattern = false;
break;
}
}
if (notASubpattern) {
patternsList.add(candidate);
}
}
}
}
Тем не менее, это невероятно медленно при поиске больших строк с тоннами шаблонов.