(UVA) What's The Frequency, Kenneth? - Solution 2

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=440

If you want to see another solution for this problem, click here.

The previous solution used a Map structure to keep the characters and its frequencies. On the other hand, this solution used only a simple array where the index is related to each character, and the content of each position is the frequency of the character.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String line = br.readLine();
        while (line != null) {
            int[] map = new int[128];
            String[] s = line.split("[\\W]"); // disconsider punctuations and spaces
            // get the frequency for each letter
            int biggestFreq = 0;
            for (int i = 0; i < s.length; i++) {
                for (int j = 0; j < s[i].length(); j++) {
                    if (s[i].charAt(j) >= '0' && s[i].charAt(j) <= '9') {
                        continue; // disconsider numbers
                    }
                    biggestFreq = Math.max(biggestFreq, ++map[s[i].charAt(j)]);
                }
            }

            int index = 0;
            // check all the characters that appear biggestFreq times
            for (int i = 0; i < 128; i++) {
                if (map[i] == biggestFreq) {
                    bw.write((char)i+"");
                }
            }
            bw.write(" "+biggestFreq+"\n");
           
            line = br.readLine();
        }          
                                              
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução