Вероятно, Map
- это одна из наиболее распространенных коллекций, которая используется для вычисления и хранения частоты чего-либо, и я использовал ее для хранения частоты желаемых последовательностей символов.
Остальная часть лога c записывается в виде комментария в коде.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) {
String str = "ABCABCDEDEDEF";
Map<String, Integer> frequencyMap = new LinkedHashMap<String, Integer>();
StringBuilder sb;
String temp, strMatch;
int counter, index, n;
boolean found, exists;
for (int i = 0; i < str.length(); i++) {
sb = new StringBuilder();
found = false;
exists = false;
counter = 0;
sb.append(str.charAt(i));// Start with charAt(i)
n = i;
// Check if `str` contains `sb`. If yes, append the next character to `sb` and
// continue the check until the last index of `sb` in `str`
while (str.contains(sb.toString()) && n < str.lastIndexOf(sb.toString())) {
found = true;
sb.append(str.charAt(++n));
}
// If while loop has been iterated, one extra character has been appended. After
// deleting this extra character, the char sequence is the desired char sequence
// whose frequency is to be found
if (found) {
sb.deleteCharAt(sb.length() - 1);
}
// Check the frequency of the desired char sequence
counter = 1;
strMatch = sb.toString();
temp = str.substring(i + sb.length());
for (int j = i + sb.length(); j < str.length(); j++) {
index = temp.indexOf(strMatch);
if (index != -1) {
counter++;
temp = temp.substring(index + strMatch.length());
} else {
break;
}
}
// Check if the char sequence is a substring of any of the existing keys in
// the map
for (String key : frequencyMap.keySet()) {
if (key.contains(sb.toString())) {
exists = true;
break;
}
}
// Add the char sequence to the map if none of its substring exists as the key
if (!exists) {
frequencyMap.put(sb.toString(), counter);
}
i += sb.length() - 1;
}
// Build the result string
StringBuilder result = new StringBuilder();
for (Entry<String, Integer> entry : frequencyMap.entrySet()) {
result.append(entry.getKey() + (entry.getValue() > 1 ? "*" + entry.getValue() + "+" : ""));
}
if (result.charAt(result.length() - 1) == '+') {
result.deleteCharAt(result.length() - 1);
}
System.out.println(result);
}
}
Вывод:
ABC*2+DE*3+F