1

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

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  
4

2 回答 2

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)elsemyMap.get(i)myMap.get(ch)

于 2012-11-15T21:08:32.693 回答
0

您正在使用字符位置初始化计数器:

myMap.put(ch, i);

你想在哪里:

myMap.put(ch, 1);

您还想在初始化计数器之前检查映射中是否存在已经存在的字符,增加它的计数器(使用get(ch)not 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
于 2012-11-15T21:09:11.553 回答