Created
September 7, 2015 10:57
-
-
Save vaibhav-jani/c6cbebfa0d26dcb0b638 to your computer and use it in GitHub Desktop.
Substring counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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