We are given a string , for example, take "TUOPPPPJHHTT" We wish to find out which character occurs the most number of times CONTINUOUSLY in the string and how many times. In this case, its P occurring 4 times.
I tried running a for loop as following
char[] array = S.toCharArray();
int count=1;
for(int i =1; i < S.length(); i++) {
if(array[i] == array[i-1]) {
count++;
}
}
but in this approach, the problem is it will count repeated occurrences of all alphabets.
Each time you find different character than previous one, it means the run (consecutive repeating alphabet) is ended, and so you should note down the length of current run (i.e., the value of count
) and then reset the count. At the end you can print the maximum.
char[] array = S.toCharArray()
int count = 1;
int max = 0;
char maxChar = 0;
for(int i=1; i<array.length; i++){ // Start from 1 since we want to compare it with the char in index 0
if(array[i]==array[i-1]){
count++;
} else {
if(count>max){ // Record current run length, is it the maximum?
max=count;
maxChar=array[i-1];
}
count = 1; // Reset the count
}
}
if(count>max){
max=count; // This is to account for the last run
maxChar=array[array.length-1];
}
System.out.println("Longest run: "+max+", for the character "+maxChar); // Print the maximum.
Here's a more generic solution that works for all characters; alphanumeric or special, doesn't matter.
private String findMaxChar(String str) {
char[] array = str.toCharArray();
int maxCount = 1;
char maxChar = array[0];
for(int i = 0, j = 0; i < str.length() - 1; i = j){
int count = 1;
while (++j < str.length() && array[i] == array[j]) {
count++;
}
if (count > maxCount) {
maxCount = count;
maxChar = array[i];
}
}
return (maxChar + " = " + maxCount);
}
System.out.println(findMaxChar("T"));
System.out.println(findMaxChar("TDD"));
System.out.println(findMaxChar("WWW"));
System.out.println(findMaxChar("NOREPEATS"));
System.out.println(findMaxChar("122333444455555"));
System.out.println(findMaxChar("abc33++$$$_###*ABCC"));
Output :
T = 1
D = 2
W = 3
N = 1 // First Character (if no repeats)
5 = 5
$ = 3
Set
to collect them as:
private static String findMaxChar(String str) {
char[] array = str.toCharArray();
Set<Character> maxChars = new LinkedHashSet<Character>();
int maxCount = 1;
maxChars.add(array[0]);
for(int i = 0, j = 0; i < str.length() - 1; i = j){
int count = 1;
while (++j < str.length() && array[i] == array[j]) {
count++;
}
if (count > maxCount) {
maxCount = count;
maxChars.clear();
maxChars.add(array[i]);
} else if (count == maxCount) {
maxChars.add(array[i]);
}
}
return (maxChars + " = " + maxCount);
}
Output :
[T] = 1
[D] = 2
[W] = 3
[N, O, R, E, P, A, T] = 1
[5] = 5
[$, #] = 3 // All Characters (in case of a tie)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With