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.
publicstaticStringhappyLadybugs(Stringb){booleanchars=b.matches("^[A-Z_]*$");booleansymbol=b.contains("_");//1st case: Check for only underscore if(!chars&&symbol){return"YES";//2nd case: if no underscore, then the given string can be already HappyLadybug// We have to find the string is adj duplicates with duplicates size > 1}elseif(chars&&!symbol){booleanisHappy=isAdjDupli(b);returnisHappy?"YES":"NO";}// count the frequency of chars, instant return NO if any char is 1.List<Integer>values=occurance(b);for(Integeri:values){if(i==1){return"NO";}}// at this point all condition meets so YESreturn"YES";}// This method to find the adjacent duplicates with >1// this helps in finding is the given string already a happyLadybugsprivatestaticbooleanisAdjDupli(Stringstr){intstart=0;intstep=1;intend=str.length()-1;intcount=1;intmin=Integer.MAX_VALUE;while(start<=end&&step<=end){if(str.charAt(start)==str.charAt(step)){step++;count++;}else{start=step;step++;min=Math.min(min,count);if(count==1){break;}else{count=1;}}}returncount==1?false:true;}//This method used to count the occurance of charprivatestaticList<Integer>occurance(Stringb){Map<Character,Integer>map=newHashMap<>();for(charc:b.toCharArray()){if(c!='_'){map.put(c,map.getOrDefault(c,0)+1);}}List<Integer>list=newArrayList<>(map.values());returnlist;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Happy Ladybugs
You are viewing a single comment's thread. Return to all comments →
Java Solution