gpt4 book ai didi

java - 这段代码有什么问题?霍夫曼编码

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:49:05 24 4
gpt4 key购买 nike

在这段代码中,我试图将一个字符串拆分为多个字符,并将每个字符放入一个映射中。如果同一个角色出现不止一次,我会在其上放置一个计数器并将其放回 map 中,增加整数(频率)。

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);

虽然我仍然不太清楚这到底是什么意思。


其次..

这些行没有意义

myMap.put(ch, i);

if(myMap.containsKey(ch)){
myMap.put(ch, myMap.get(i) + 1);
}

您刚刚添加了 key ch然后你立即询问 map 是否包含 ch - 这将永远是正确的。

我想你可能想把 if -statement first 并放置 myMap.put(ch, <b>1</b>)else -条款。哦,还有myMap.get(i)可能应该是myMap.get(ch) .

关于java - 这段代码有什么问题?霍夫曼编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com