Problem H
Tell me the frequencies!
Input: standard input
Output: standard output
Given a line of text you will have to find out the frequencies of the ASCII characters present in it. The given lines will contain none of the first 32 or last 128 ASCII characters. Of course lines may end with ‘\n’ and ‘\r’ but always keep those out of consideration.
Input
Several lines of text are given as input. Each line of text is considered as a single input. Maximum length of each line is 1000.
Output
Print the ASCII value of the ASCII characters which are present and their frequency according to the given format below. A blank line should separate each set of output. Print the ASCII characters in the ascending order of their frequencies. If two characters are present the same time print the information of the ASCII character with higher ASCII value first. Input is terminated by end of file.
Sample Input:
AAABBC122333
Sample Output:
67 166 2
65 3
49 1
50 2
51 3
解法:儲存後排序 or 開表格紀錄
import java.util.Scanner;
public class UVA10062 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean check = false;
while (sc.hasNext()) {
if (check)
System.out.println();
int count = 0;
int matrix[] = new int[97];
String s = sc.nextLine();
for (int i = 0; i < s.length(); i++) {
matrix[s.charAt(i) - 32]++;
count++;
}
for (int i = 1; i <= count; i++) {
for (int j = 96; j >= 0; j--) {
if (matrix[j] == i)
System.out.println((j + 32) + " " + i);
}
}
check = true;
}
sc.close();
}
}
-----------------------------------------------------------------------------------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String m = "";
boolean check = false;
while ((m = br.readLine()) != null) {
if (check)
sb.append("\n");
matrix[] arr = new matrix[97];
for (int i = 0; i < 97; i++) {
arr[i] = new matrix(0, (char) (i + 31));
}
for (int i = 0; i < m.length(); i++) {
arr[m.charAt(i) - 31].ic_count();
}
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
if (arr[i].getCount() > 0) {
sb.append(arr[i].getC() + " " + arr[i].getCount() + "\n");
}
}
check = true;
}
System.out.print(sb);
}
}
class matrix implements Comparable<matrix> {
int count = 0;
char c = 0;
public matrix(int num, char temp) {
count = num;
c = temp;
}
public void ic_count() {
count++;
}
public int getC() {
return c;
}
public int getCount() {
return count;
}
@Override
public int compareTo(matrix i) {
if (count > i.getCount())
return 1;
else if (count == i.getCount()) {
if (c > i.getC())
return -1;
else
return 1;
}
return -1;
}
}
留言
張貼留言