• + 0 comments

    Java solution:

    public static boolean isValidateString(String s){
            int n = s.length(); 
            for(int i = 1; i < n; i++){
                char current = s.charAt(i);
                if(current == s.charAt(i-1))
                    return false;    
                }
            return true; 
           }
    			 
    			 public static int alternate(String s) {
            int n = s.length();
            Set<String> set = new HashSet<String>( Arrays.asList(s.split("") )  );
            for(int i = 1; i < n; i++){
                char current = s.charAt(i);
                if(current == s.charAt(i-1)){
                    set.remove(String.valueOf(current) );
                    }
                }
            int m = set.size();
            String[]elements = set.toArray(new String[m]);
            int maxLen = 0;
            
            for(int i = 0; i < m-1; i++)
                for(int j = i+1; j < m; j++){
                    char c1 = elements[i].charAt(0);
                    char c2 = elements[j].charAt(0);
                    String result = "";
                    for(int k = 0; k < n; k++){
                        char curr = s.charAt(k);
                        if(curr == c1 || curr == c2)
                          result += curr;
                        }
                    if(isValidateString(result))
                        maxLen = Math.max(maxLen, result.length());
                    }
            return maxLen;
    
            }