• + 0 comments

    Java soluation using HashMap:

     public static String happyLadybugs(String b) {
            HashMap<Character, Integer> colors = new HashMap<>();
            int n = b.length();
            boolean contain_underscore = false;
            boolean same_color_adjacent = true;
            char prev = ' ';
            
            for(int i = 0; i < n; i++){
                char c = b.charAt(i);
                if(c == '_') contain_underscore = true;
             
                else{
                  if (i > 0 && !contain_underscore && c != prev && colors.get(prev) <= 1)
                       same_color_adjacent = false; 
                  prev = c;
                    
                    
                  if(!colors.containsKey(c))
                        colors.put(c, 1);
                  else
                        colors.replace(c, colors.get(c) + 1);  
                  }
                 
                }
            
            if(!contain_underscore && !same_color_adjacent)
                return "NO";
            
            for(Integer val:colors.values())
                if(val <= 1)
                    return "NO";
            
            return "YES"; 
            
            }