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

…衆ロ難τιáo~ 提交于 2019-11-29 17:58:18
    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.

TheLostMind
  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

First in initialize the arr[] i.e

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);


}
}

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!