The following method receives a string and finds all occurrences of repeated substrings with a length of three characters, including spaces. Is this a good approach?
public Map<String, Integer> findOccurences(String str) {
Map<String, Integer> map = new HashMap<String, Integer>();
int counter = 0;
String sub;
int stringLen = str.length() - 2;
for (int i = 0; i < stringLen ; i++) {
sub = str.substring(i, i + 3);
if (map.containsKey(sub)) {
counter = map.get(sub);
counter++;
map.put(sub, counter);
counter = 0;
} else {
map.put(sub, 1);
}
}
return map;
}
Input
This This
Output
Th 1 <<< includes space s T 1 his 2 Thi 2 is 1 <<< includes space