日期:2014-05-20  浏览次数:20660 次

面试题:统计单词中各个字母出现的次数?
面试题:统计单词中各个字母出现的次数?

------解决方案--------------------
Java code

/**
     * 检索一段字符串中每个字符出现的次数
     * @param args
     * @return
     */
    public static Map<Character, Integer> charNonu(char args[]) {
        Map<Character, Integer> map = new TreeMap<Character, Integer>();
        for(int i = 0; i < args.length; i++) {
            char temp = args[i];
            if(!map.containsKey(temp)) {
                map.put(temp, 1);
            }else {
                int auto = map.get(temp)+1;
                map.put(temp, auto);
            }
        }
        return map;
    }

------解决方案--------------------
Java code
package com.studjava;

import java.util.ArrayList;
import java.util.List;

public class Test11 {   
 /**  
 * @param args  
 */   
 public static void main(String[] args) {   
     String a = "abcdBbefgaAAA";  
     //a = a.toLowerCase() ;  //如果要统计不区分大小写的话 ,就统一转换为小写或者大写
     int [] ii = new int[256] ;
     List list = new ArrayList() ;
     char[] cs = a.toCharArray();   
     for (char c : cs) {   
         if (ii[c] == 0){
             list.add(c) ;
         }
         ii[c] =  ii[c] + 1;   
     }   
    
     char ch ;
     for (int i = 0; i < list.size(); i++){
         ch = (Character) list.get(i) ;
         System.out.println(ch + "  出现次数: " + ii[ch]) ;
     }
 }   
}