We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticStringisValid(Strings){// Write your code hereHashMap<Character,Integer>letterCountMap=newHashMap<>();HashMap<Integer,Integer>occMap=newHashMap<>();// count letterfor(Characterch:s.toCharArray()){letterCountMap.put(ch,letterCountMap.getOrDefault(ch,0)+1);}// count of occurences of the occurences of the letterfor(Map.Entry<Character,Integer>entry:letterCountMap.entrySet()){occMap.put(entry.getValue(),occMap.getOrDefault(entry.getValue(),0)+1);}// if all equalif(occMap.size()==1)return"YES";// find largest count & smallest count// don't really need to keep track of smallest & largest// only need to store the 2 key value into variable for comparing laterintlargest_key=Integer.MIN_VALUE;intsmallest_key=Integer.MAX_VALUE;intlargest_value=0;intsmallest_value=0;for(Map.Entry<Integer,Integer>entry:occMap.entrySet()){if(entry.getValue()>largest_key){largest_key=entry.getKey();largest_value=entry.getValue();}if(entry.getValue()<smallest_key){smallest_key=entry.getKey();smallest_value=entry.getValue();}}// System.out.println("count map: " + letterCountMap);// System.out.println("occ map: " + occMap);// System.out.println("largest: " + largest_key);// System.out.println("smallest: " + smallest_key);if(occMap.size()==2){if(occMap.get(smallest_key)==1||occMap.get(largest_key)==1)if(smallest_key==1||largest_key==1)return"YES";elseif(Math.abs(smallest_key-largest_key)==1)return"YES";}return"NO";}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and the Valid String
You are viewing a single comment's thread. Return to all comments →
Java Solution