简体   繁体   中英

Java program to find the character that appears the most number of times in a String?

So here's the code I've got so far...

import java.util.Scanner;
class count{
    public static void main(String args[]){
        Scanner s=new Scanner(System.in);
        System.out.println("Enter a string");
        String sent=s.nextLine();
        int len = sent.length();
        int arr[]=new int[len];
        int count=1;
        char ch[] = new char[len];
        for(int i = 0; i <= len-1; i ++)
        {
            ch[i] = sent.charAt(i);

        }
        for(int j= 0;j<=len-1;j++){
            for(int k=0;k<=len-1;k++){
                if(ch[j]==ch[k]){
                    arr[j]= count++;
                }
            }
        }

        int max=arr[0];
        for(int z=1;z<=len-1;z++){
            if(count>max)
                max=count;
        }
        System.out.println(max);
        System.out.println("The character that appears the most number of times is "  +arr[max]);
    }
}

I get count to display the number of times each character appears in the string, I'm not able to compare it with the rest of the elements in the array.

The number of appearances is stored in array 'arr[]' how do I find the largest integer in this array? And Also, how do I display the character that has appeared the maximum number of times?

The logic of the code isn't working after,

  int max=arr[0];

Any ideas as to what to do?

  1. Use Collections . Simple and easy.
  2. Use HashMap <Character,Integer> .
  3. parse the String you have read. For each character in the string, check if it is available in the map (as key). If yes, increment the count, else add the character to the map as key and set the count to 0.
  4. sort the map
    String sent = "asdAdFfaedfawghke4";//s.nextLine();      
    int length = sent.length();
    char frequentChar = ' ';
    int maxLength = 0;
    for (int i = 0; i < length; i++) {
        char currentChar = sent.charAt(0);
        sent = sent.replaceAll(currentChar + "", "");//remove all charactes from sent
        if (maxLength < (length - sent.length())) {
            frequentChar=currentChar;
            maxLength = length - sent.length();
        }
        System.out.println("Char : " + currentChar + " Occurance " + (length - sent.length()));
        length = sent.length();
    }
    System.out.println("Max Occurance : " + maxLength);

Output :

Char : a Occurance 3
Char : s Occurance 1
Char : d Occurance 3
Char : A Occurance 1
Char : F Occurance 1
Char : f Occurance 2
Char : e Occurance 2
Frequent Char : a
Max Occurance : 3
  • Build the HashMap with Int = number of times that Char appears in the input string; in O(n) where n=length of the input string.
  • Find the maximum value in HashMap in O(m) where m is the number of unique characters in the input string.
  • Overall, the complexity is O(n) since n>m.

Tips: When you are building the HashMap, at the same time, you can store the maximum value and corresponding character. Still O(n) but the code would be cleaner.

First in initialize the arr[] ie

for(int i=0;i<len-1;i++{
arr[i]=0;
}

then :

for(int j= 0;j<=len-1;j++){
  count=0;
  for(int k=0;k<=len-1;k++){
      if(ch[j]==ch[k]){
          arr[j]= count++;
    }
  }
}

You can use the following logic to get the max occured char. The below program will convert the whole string into uppercase after that it will count the max occured char and it it will print the char in upperCase.

import java.util.Scanner;
class Mostchar{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("Enter a string");
String sent=s.nextLine();
sent = sent.toUpperCase();
System.out.println(sent);
int len = sent.length();
int arr[]=new int[26];
int max=0;
char ch=0;
for(int i=0;i<len;i++)
{
    arr[sent.charAt(i)-65] = arr[sent.charAt(i)-65] + 1;
    if(arr[sent.charAt(i)-65]>max)
    {
        max = arr[sent.charAt(i)-65];
        ch=sent.charAt(i);
    }
}
System.out.println("Max occured char is: "+ch+" , times: "+max);


}
}

I would do something like this

    String str = "yabbadabbadoo";
    Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>() ;
    for (int x = 0; x < str.length(); x++) {
        Integer idx = (int) str.charAt(x);
        Integer got = ht.get(idx);
        if (got == null) {
            ht.put(idx, 1);
        } else {
            ht.put(idx, got.intValue() + 1);
        }
    }

    int max = 0;
    char ch = '-';
    Enumeration<Integer> keys = ht.keys();
    while (keys.hasMoreElements()) {
        Integer idx = keys.nextElement();
        int count = ht.get(idx);
        if (count > max) {
            ch = (char) idx.intValue();
            max = count;
        }
    }

    System.out.print("[" + ch + "]");
    System.out.println(" Max " + max);

Keep in mind about upper and lower case characters

the variable count needs the value to be reset after every iteration of k so it will look like this

    for(int j= 0;j<=len-1;j++){
        for(int k=0;k<=len-1;k++){
            if(ch[j]==ch[k]){
                arr[j]= count++;
            }
        }count=1;
    }

moreover when you are trying to find the maximum in the array it would be easier and correct in this.

    int max=0;
    for(int z=1;z<=len-1;z++){
        if(arr[z]>arr[max])
            max=z;
    }

what you are doing (rather what it would have done had count been reset) is storing the occurrence count of first character and then comparing it with the no. of occurrences of last character and if more then last character occurrences with itself.

Let's say you have this example:

BACAVXARB

Then your output for your 1st array ch would be:

ch[0]=B
ch[1]=A
ch[2]=C
ch[3]=A
ch[4]=V
ch[5]=X
ch[6]=A
ch[7]=R
ch[8]=B

Then the next output would be:

arr[0]=2
arr[1]=3
arr[2]=1
arr[3]=3
arr[4]=1
arr[5]=1
arr[6]=3
arr[7]=1
arr[8]=2

But that output would be wrong 'cause counter, never resets, so we make this:

for(int j= 0;j<=len-1;j++){
    for(int k=0;k<=len-1;k++){
        if(ch[j]==ch[k]){
            arr[j]= count++;
        }
    }
    count=1;
}

Then, your max variable would be:

max=2

So, here we have a problem on your last for, I made this one, using my own variables:

int newCounter;
for(i=0; i<= len-1; i++){
    if(arr[i]>max){
        max = arr[i];
        newCounter = i; //We create this new variable, to save the position, so we will always have the same counter on arr[i] and ch[i]
    }
}

All the missing part is:

System.out.println("The character that repeats the most is: " + ch[newCounter]);

And output should be: The character that repeats the most is: A

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM