java面试题答案

package test;


public class TestFrequency {
 
 private static int MAX_COUNT = 26;
 
 public static void frequency(String str) {
  str = str.toUpperCase();
  int[] ilist = new int[MAX_COUNT];
  int[] vlist = new int[MAX_COUNT];
  
  for (int i = 0; i < MAX_COUNT; i++) {
   ilist[i] = i;
   vlist[i] = 0;
  }
 
  for (int i = 0; i < str.length(); i++) {
   char c = str.charAt(i);
   int index = c - 65;
   
   if ((index >= 0) && (index < MAX_COUNT)) {
    vlist[index] = vlist[index] + 1;
   }
  }
  
  for (int i = 0; i < MAX_COUNT; i++) {
   for (int j = i + 1; j < MAX_COUNT; j++) {
    if (vlist[j] > vlist[i]) { 
     int tempIndex = ilist[j];
     ilist[j] = ilist[i];
     ilist[i] = tempIndex;
     
     int tempMax = vlist[j];
     vlist[j] = vlist[i];
     vlist[i] = tempMax;
    }
   }
  }
  
  for (int i = 0; i < MAX_COUNT; i++) {
   char c = (char)(ilist[i] + 65);
   String v = String.valueOf(vlist[i]);
   System.out.println(c + "---" + v);
  }
 }
 
 public static void main(String[] args) {
  frequency("bbbaak;jhnwe;oroihgggggggggggggggggggggggggggggggggggggggggggggggggpacahnszzzzzzepru qwehruoiv weyrasdfasdfawefawerawac");
 }
}
 

你可能感兴趣的:(java面试题答案)