• + 0 comments

    My Java Solution

    public static String happyLadybugs(String b) {
            String[] bugArr = b.split("");
            if(b.contains("_")){
                Arrays.sort(bugArr);
            }
            bugArr = Arrays.stream(bugArr)
                    .filter(s -> !s.equals("_"))
                    .toArray(String[]::new);
            boolean isPresent = false;
    
            if(bugArr.length == 0){
                return "YES";
            }
    
            if(bugArr.length > 1){
                if(!bugArr[0].equalsIgnoreCase(bugArr[1])
                        || !bugArr[bugArr.length-1].equalsIgnoreCase(bugArr[bugArr.length-2])){
                    return "NO";
                }
                for(int i=1; i<bugArr.length-1; i++){
                    String currentElement = bugArr[i];
                    if(currentElement.equals(bugArr[i-1]) || currentElement.equals(bugArr[i+1])){
                        isPresent = true;
                    }else{
                        isPresent = false;
                        break;
                    }
                }
            }
    
            return isPresent ? "YES" : "NO";
        }