在这段代码中,我试图将字符串拆分为字符并将每个字符放入映射中。如果同一个字符多次出现,我会在其上放置一个计数器并将其放回地图中,增加整数(频率)。
public class FrequencyMap {
public static Map<Character, Integer> generateMap(String s){
HashMap<Character, Integer> myMap = new HashMap<Character, Integer>();
//generate a map of frequencies of the characters in s
//need to break the string down into individual characters, sort them
//in there frequencies then place them in map
for(int i = 0; i < s.length(); i++){
//break string into characters
//need to determine how many characters make up the string, can do this by
//putting a counter on each letter that appears when the string is being
//broken down, if a letter reoccurs increment the counter by one.
s.substring(i);
char ch = s.charAt(i);
myMap.put(ch, i);
//calculating the occurence of a character in a string.
if(myMap.containsKey(ch)){
myMap.put(ch, myMap.get(i) + 1);
}//end of if statement
}//end of for loop
return myMap;
}//end of public generateMap()
}//end of FrequencyMap
这里是主要的
public static void main(String args[]){
String str = "missisippi";
Map frequencyMap = FrequencyMap.generateMap(str);
HuffmanTree tree = new HuffmanTree(frequencyMap);
Map<Character, String> encodingMap = tree.getEncodingMap();
String encoded = tree.encode(str, encodingMap);
System.out.println(encoded);
}//end of main