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ます。これは常に当てはまります。

-statementを最初に置き、if-clauseを入れるつもりだったのではないかと思います。ああ、おそらくそうすべきだった。myMap.put(ch, 1)elsemyMap.get(i)myMap.get(ch)

于 2012-11-15T21:08:32.693 に答える
0

You are initialising your counters with the character position:

myMap.put(ch, i);

where you want:

myMap.put(ch, 1);

You also want to check the map for an already existing character before you initialise the counter, incrementing the counter of it does (using get(ch) not get(i)), giving:

    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 に答える