【发布时间】:2012-11-15 20:57:50
【问题描述】:
在这段代码中,我试图将字符串拆分为字符并将每个字符放入映射中。如果同一个字符多次出现,我会在其上放置一个计数器并将其放回地图中,增加整数(频率)。
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
【问题讨论】:
-
您的代码遇到了什么问题?
-
s.substring(i);行是空操作。您获取s的子字符串,然后将其丢弃。 -
快速浏览一下。
s.substring(i);没有改变s。 -
在
char ch = s.charAt(i); myMap.put(ch, i);之后,myMap将始终包含ch的映射。在查看内部之前,您不应该插入任何东西。 -
戴夫,也许你应该回去接受一些关于你以前的问题的答案。如果人们认为您无论如何都不会看答案,他们可能不太可能提供帮助。
标签: java algorithm map huffman-code