在这段代码中,我试图将字符串拆分为字符并将每个字符放入地图中。如果同一个角色出现不止一次,我会在其上放置一个计数器并将其放回到地图中,然后递增整数(频率)。
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
答案 0 :(得分:2)
好的一些事情......
字符串是不可改变的!!
s.substring(i);
应该是
s = s.substring(i);
虽然我还不太确定这一点是什么意思。
其次..
这些行没有意义
myMap.put(ch, i);
if(myMap.containsKey(ch)){
myMap.put(ch, myMap.get(i) + 1);
}
您刚刚添加了密钥ch
,然后您立即询问地图是否包含ch
- 这将始终为真。
我认为您可能打算将if
- 语句放在第一个并将myMap.put(ch, 1)
放入else
- 子句中。哦,myMap.get(i)
可能应该是myMap.get(ch)
。
答案 1 :(得分:0)
您正在使用角色位置初始化您的计数器:
myMap.put(ch, i);
你想要的地方:
myMap.put(ch, 1);
您还需要在初始化计数器之前检查已存在的字符的地图,增加计数器的计数器(使用get(ch)
而不是get(i)
),给出:
char ch = s.charAt(i);
//calculating the occurence of a character in a string.
if (myMap.containsKey(ch)){
myMap.put(ch, myMap.get(ch) + 1);
} else {
myMap.put(ch, 1);
}//end of if statement