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){HashMap<Character,Integer>charFreqs=newHashMap<Character,Integer>();for(inti=0;i<s.length();i++){//Get the frequencies of each characterchara=s.charAt(i);if(charFreqs.containsKey(a))charFreqs.replace(a,charFreqs.get(a)+1);elsecharFreqs.put(a,1);}List<Integer>freqList=newArrayList<Integer>();booleansafeToRemove=true;//Flag for if we've already removed a single characterfor(charkey:charFreqs.keySet()){//Create a list of all character frequencies, then sort itfreqList.add(charFreqs.get(key));}Collections.sort(freqList);intminFreq=freqList.get(0);//The minimum frequency that isn't 1 is our target value, since we can only remove characters from the string.if(minFreq==1){//If there's a single instance of a given character...safeToRemove=false;if(freqList.size()>1)minFreq=freqList.get(1);//...use the second frequency if the list of frequencies has more than one element.}for(intj=1;j<freqList.size();j++){intfreq=freqList.get(j);System.out.println(freq);if(freq==1&&!safeToRemove)return"NO";//There are multiple characters for which only one instance occurs.elseif(freq-minFreq==1){//If we've already removed a character, we can't remove another. So check if we didn't already do so and then set that flag to false if such is the case.if(safeToRemove)safeToRemove=false;elsereturn"NO";}elseif(freq-minFreq>1)return"NO";//If a frequency exists that's greater than 1 + the minimum frequency, the string isn't valid.}return"YES";}
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 15 solution that passes all test cases: