Home > Back-end >  JAVA logic: How to remove only max occurrence of given character?
JAVA logic: How to remove only max occurrence of given character?

Time:07-21

Input: 567000003460046
Output: 5673460046
(As 0 was present 5 times and 2 times but we have to remove the max presence and retain remaining.)

CodePudding user response:

The below code iterates through the characters in the input. It counts consecutive digits and determines the maximum number of consecutive digits as well as what that digit is. It then creates a string containing the maximum digit, the maximum number of consecutive occurrences. For the example input in your question, that means means a string of five 0 (zero), i.e. 00000. Finally, it removes the string of five 0 by replacing it with an empty string.

public class Main {

    public static void main(String[] args) {
        String input = "567000003460046";
        System.out.println(" Input: "   input);
        char current = '\u0000'; // Unicode code point for null character.
        char maxChar = current;
        int count = 0;
        int max = 0;
        for (char ch : input.toCharArray()) {
            if (ch != current) {
                if (count > max) {
                    max = count;
                    maxChar = current;
                }
                count = 0;
                current = ch;
            }
            count  ;
        }
        StringBuilder remove = new StringBuilder(max);
        for (int i = 0; i < max; i  ) {
            remove.append(maxChar);
        }
        String output = input.replaceAll(remove.toString(), "");
        System.out.println("Output: "   output);
    }
}

Running the above code produces the following output:

 Input: 567000003460046
Output: 5673460046
  • Related