Title: "AABABCABCDABCDE", obtaining the number of occurrences of each letter in a string results: A (5) B (4) C (3) d (2) e (1)
At first may not be able to do this problem, and now step into the analysis
1: First it is a string, but to analyze each character the number of times it appears, then it must be a loop traversal, to traverse the general is either a collection, or an array, and here it is better to become an array,
2: After becoming an array, we can use a map set to store characters and occurrences of the number of times that is, the key is Character,value is an integer, and then at the time of traversal to take the key to get value values to judge if value is null, It means that the number of characters in the collection is 1, and if it is not NULL, the character is represented in the collection, and the number of occurrences is + +, and then stored in the collection
3: After doing the above operation to traverse the collection, but with what set is better, we found that it requires the output of the result is a,b,c this dictionary order, the map collection has this function can be used TreeMap
Code:
Package Cn.kge.collection;import Java.util.set;import Java.util.treemap;public class MapDemo1 {public static void Main (string[] args) { String str = "AABABCABCDABCDE"; treemap<character,integer> map = new treemap<character,integer> (); char[] CHS = Str.tochararray (); for ( Character ch:chs) {Integer value = map.get (ch), if (value==null) {map.put (ch, 1);} Else{value++;map.put (ch, value);}} set<character> set = Map.keyset (); StringBuilder sb = new StringBuilder (); for (Character s:set) {Integer value = Map.get (s); Sb.append (s). Append ("("). Append (Value). Append (")");} System.out.println (Sb.tostring ());}}
Java face question "AABABCABCDABCDE", gets the number of occurrences of each letter in a string requires results: A (5) B (4) C (3) d (2) e (1)