All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0801_0900.s0811_subdomain_visit_count.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0801_0900.s0811_subdomain_visit_count;

// #Medium #Array #String #Hash_Table #Counting

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List subdomainVisits(String[] d) {
        Map fmap = new HashMap<>();
        for (String s : d) {
            int rep = 0;
            int i;
            for (i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c >= '0' && c <= '9') {
                    rep = rep * 10 + (c - '0');
                } else {
                    break;
                }
            }
            String str = s.substring(i + 1);
            seperate(rep, str, fmap);
        }
        List res = new ArrayList<>();
        for (Map.Entry entry : fmap.entrySet()) {
            String comp = "";
            comp += entry.getValue();
            comp += " ";
            comp += entry.getKey();
            res.add(comp);
        }
        return res;
    }

    private void seperate(int rep, String s, Map fmap) {
        int i = s.length() - 1;
        while (i >= 0) {
            String toHash;
            while (i >= 0 && s.charAt(i) != '.') {
                i--;
            }
            toHash = s.substring(i + 1);
            fmap.put(toHash, fmap.getOrDefault(toHash, 0) + rep);
            i--;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy