`

得到一个字符串中所有字母的重复次数,并得到重复最多的那个字母。

阅读更多
package com.java.examples.string;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 得到一个字符串中所有字母的重复次数,并得到重复最多的那个字母。
 * @author yuahan
 *
 */
public class StringMaxCharacterNumber {
	
	public static Map<String,Integer> getMaxCharacterAndNum(String input){
		Map<String,Integer> result = new HashMap<String,Integer>();
		
		Map<String,Integer> map = new HashMap<String,Integer>();
		for(int i=0;i<input.length();i++){
			char c = input.charAt(i);
			if(c >= 'a' && c <= 'z' || c >= 'A' && c<= 'Z'){
				String key = String.valueOf(c);
				if(map.containsKey(key)){
					int count = map.get(key);
					map.put(key, ++count);
				}else{
					map.put(key, 1);
				}
			}
		}
		
		Iterator<String> iter = map.keySet().iterator();
		StringBuffer sb = new StringBuffer();
		int max = 0;
		while(iter.hasNext()){
			String key = iter.next();
			int count = map.get(key);
			if(count > max){
				max = count;
				sb = new StringBuffer();
				sb.append(key + ",");
			}else if(count == max){
				sb.append(key + ",");
			}
		}
		
		result.put(sb.toString(), max);
		return result;
	}
	
	public static void main(String[] args) {
		String input = "a  234a  bbb  c   ccdddde  .,,/,/,;l;,eeff  fgggg";
		Map<String,Integer> result = StringMaxCharacterNumber.getMaxCharacterAndNum(input);
		String str = result.keySet().iterator().next();
		int max = result.get(str);
		str = str.substring(0, str.length() - 1);
		System.out.println(str + "\t" + max);
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics