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

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


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) {
            Map<Character, Integer> map = new TreeMap<>();
            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
                    }
                    if (!map.containsKey(s[i].charAt(j))) { // consider only letters
                        map.put(s[i].charAt(j), 0);
                    }
                    map.put(s[i].charAt(j), map.get(s[i].charAt(j))+1);
                    biggestFreq = Math.max(biggestFreq, map.get(s[i].charAt(j)));
                }
            }

            int index = 0;
            // check all the characters that appear biggestFreq times
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                if (entry.getValue() == biggestFreq) {
                    bw.write(entry.getKey()+"");
                }
            }
            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