美団実習生試験問題1
5867 ワード
符号化後の文字列の長さが最も短くなるように、アルゴリズムを設計してください.
import java.util.*;
import java.util.Map.Entry;
public class lessStep {
public static class Words implements Comparable{
public Words(Integer count){
this.count=count;
}
Words left,right;
Integer count;
public int weight;
public Words getLeft() {
return left;
}
public void setLeft(Words left) {
this.left = left;
}
public Words getRight() {
return right;
}
public void setRight(Words right) {
this.right = right;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Words word=(Words) o;
if(word.count>count) return 1;
else return -1;
}
}
int lessSteps(Words word,int height){
if(word.left==null&&word.right==null) return word.count*height;
else return lessSteps(word.left,height+1)+lessSteps(word.right,height+1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
while(scan.hasNext()){
String str=scan.next();
Map map=new HashMap();
char[] alpha=str.toCharArray();
for(int i=0;iif(map.get(alpha[i]-0)==null) map.put((int)alpha[i],1);
else map.put((int)alpha[i],map.get(alpha[i]-0)+1);
System.out.println(map.size()+"----");
Iterator> iter=map.entrySet().iterator();
List list=new ArrayList();
while(iter.hasNext()){
Words word=new Words(iter.next().getValue());
list.add(word);
}
while(list.size()>1){
Collections.sort(list);
Words left=list.get(0),right=list.get(1);
Words word=new Words(left.count+right.count);
System.out.println(left.count+","+right.count);
word.left=left;
word.right=right;
list.remove(1);
list.remove(0);
list.add(word);
}
System.out.println(new lessStep().lessSteps(list.get(0),0));
}
}
}