算法題:統計出現次數最多的字符

(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+"次");
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章