算法题:统计出现次数最多的字符

(1)方法1
双重for循环

public void test1(){
		String str="agfsgsghdshdhasgdsgasgsagsdgdgdhshdh";
		
		char res=str.charAt(0);
		int max=0;
		System.out.println(res);
		for (int i = 0; i < str.length(); i++) {
			char temp=str.charAt(i);
			int count=0;
			for (int j = 0; j < str.length(); j++) {
				if (str.charAt(j)==temp) {
					count++;
					
				}
			}
			if (count>max) {
				max=count;
				res=temp;
				
			}
		}
		System.out.println(res+"出现次数最多:"+max+"次");
	}

(2)方法2
使用HashMap

public void test2() {
		String str="agfsgsghdshdhasgdsgasgsagsdgdgdhshdh";//统计每个字符出现的次数
		Map<Character, Integer> map=new HashMap<Character, Integer>();
		char res=str.charAt(0);
		int max=0;
		for (int i = 0; i < str.length(); i++) {
			char c=str.charAt(i);
			Integer count = map.get(c);
			if (count==null) {//字符没有出现过
				map.put(c,1);
			} else {//字符出现过
				map.put(c,count+1);
			}
		}
		for (Character key:map.keySet()) {
			Integer value=map.get(key);
			if (value>max) {
				max=value;
				res=key;
				
			}
			System.out.println(key+":"+value);
		}
		System.out.println(res+"出现次数最多:"+max+"次");
	}

你可能感兴趣的:(java,算法)