Skip to main content
4 of 6
added 1116 characters in body

This algorithm will work perfectly fine for what you want to develop:

Before that, let me make it clear that you mentioned a situation where you want to check repeatitions of 2 different characters same number of times, for that you have to run a for loop in reverse to identify the 2nd character. So if the 2nd character is not same as the first one identified, and also if it's number of repeatitions are the same, you print both the characters or else, just print the single character you find at the first for loop because both the characters are going to be same.

Run a reverse for loop like this given below in your length function after the first for loop. Make sure to reset the variables that you are going to use again. This will identify another position of the variable that is repeating maximum times. But since a function can only return 1 value, use this reverse algorithm in a different function and have what you want to achieve.

for(int i=size-1;i>0;i--){  
   if(A[i].equals(A[i-1])){  
       current++;  
   }  
   else{  
       if(current>res){  
           index=i-current;  
           res=current;  
       }  
       current=1;  
   }  
}  

Incase you need more reference, here is my own code which works exactly as you want but don't use this algorithm and implement it directly as it will limit your thinking of generating new algorithms your way.(Migrated from the same question you asked on this link at StackOverflow.

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter String 1: ");
    String A1 = sc.nextLine();
    
    MaxRepeat(A1);
}

public static void MaxRepeat(String A) {
    int count = 1;
    int max1 = 1;
    char mostrepeated1 = ' ';
    for(int i = 0; i < A.length()-1;i++) {
        char number = A.charAt(i);

        if(number == A.charAt(i+1)) {
            count++;
            if(count>max1) {
                max1 = count;
                mostrepeated1 = number;
            }
            continue;
        }
            count = 1;
    }
    
    count = 1;
    int max2 = 1;
    char mostrepeated2 = ' ';
    for(int i = A.length()-1; i>0; i--) {
        char number = A.charAt(i);

        if(number == A.charAt(i-1)) {
            count++;
            if(count>max2) {
                max2 = count;
                mostrepeated2 = number;
            }
            continue;
        }
            count = 1;
    }
    
    if((max1==max2) && (mostrepeated1==mostrepeated2)) {
        System.out.println("Most Consecutively repeated character is: " + mostrepeated1 + " and is repeated " + max1 + " times.");
    }
    
    else if((max1==max2) && (mostrepeated1!=mostrepeated2)) {
        System.out.println("Most continously repeated characters are: " + mostrepeated1 + " and " + mostrepeated2 + " and they are repeated " + max1 + " times");
    }
}