(UVA) Memory Overflow - Solution 2

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

The difference between this solution and the previous one is that the StringBuilder is not used here. Instead, it is used a HashMap structure that gives all the characters that are in the memory.


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

class Main {
    public static void process() throws NumberFormatException, IOException {  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String line = br.readLine();
        int numTests = Integer.parseInt(line);
        for (int i = 0; i < numTests; i++) {
            line = br.readLine();
            String[] s = line.split("\\s");
           
            int numNames = Integer.parseInt(s[0]);
            int memory = Integer.parseInt(s[1]);
            String names = s[2];
           
            int answer = 0;
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            for (int j = 0; j < names.length(); j++) {
                if (map.containsKey(names.charAt(j)) && map.get(names.charAt(j)) > 0) {
                    answer++;
                }
               
                if (!map.containsKey(names.charAt(j))) {
                    map.put(names.charAt(j), 1);
                }
                else {
                    map.put(names.charAt(j), map.get(names.charAt(j))+1);
                }
               
                if (j >= memory) {
                    map.put(names.charAt(j-memory), map.get(names.charAt(j-memory))-1);
                }
            }
           
            System.out.println("Case " + (i+1) + ": " + answer);
        }
                   
        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