Skip to content

Instantly share code, notes, and snippets.

@vaibhav-jani
Created September 7, 2015 10:57
Show Gist options
  • Select an option

  • Save vaibhav-jani/c6cbebfa0d26dcb0b638 to your computer and use it in GitHub Desktop.

Select an option

Save vaibhav-jani/c6cbebfa0d26dcb0b638 to your computer and use it in GitHub Desktop.
Substring counter
import java.util.HashMap;
import java.util.Map;
public class HelloWorld {
public static void main(String[] args) {
String str = "this is what this is";
System.out.println(str);
Map<String, Integer> map = findOccurences(str, 3);
for (String string : map.keySet()) {
System.out.println(string + " : " + map.get(string));
}
}
public static Map<String, Integer> findOccurences(String str, int count) {
Map<String, Integer> map = new HashMap<String, Integer>();
String sub;
int stringLen = str.length() - (count - 1);
for (int i = 0; i < stringLen; i++) {
sub = str.substring(i, i + count);
if (map.containsKey(sub)) {
int counter = map.get(sub);
counter++;
map.put(sub, counter);
counter = 0;
} else {
map.put(sub, 1);
}
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment