PAT 1042 字符統計 (20分)(Java)

題目描述

  請編寫程序,找出一段給定文字中出現最頻繁的那個英文字母。

輸入格式:

  輸入在一行中給出一個長度不超過 1000 的字符串。字符串由 ASCII 碼錶中任意可見字符及空格組成,至少包含 1 個英文字母,以回車結束(回車不算在內)。

輸出格式:

  在一行中輸出出現頻率最高的那個英文字母及其出現次數,其間以空格分隔。如果有並列,則輸出按字母序最小的那個字母。統計時不區分大小寫,輸出小寫字母。

輸入樣例:

This is a simple TEST.  There ARE numbers and other symbols 1&2&3...........

輸出樣例:

e 7

實現

package com.hbut.pat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Pat_1042 {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s = br.readLine().toLowerCase().replaceAll("\\s+", ""); 
		int[] a = new int[128];
		int max = 0;
		int maxz = 128;
		for (int i = 0; i < s.length(); i++) {
			a[s.charAt(i)]++;
			
			if (a[s.charAt(i)] > max && s.charAt(i) >= 97 && s.charAt(i) <= 122) {
				max = a[s.charAt(i)];
				maxz = s.charAt(i);
			}
			
			if (a[s.charAt(i)] == max && s.charAt(i) >= 97 && s.charAt(i) <= 122) {
				if (s.charAt(i) < maxz) {
					max = a[s.charAt(i)];
					maxz = s.charAt(i);
				}
			}
		}
		System.out.println((char) maxz + " " + max);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章