0

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?

Suhaib Janjua
  • 3,273
  • 13
  • 52
  • 68
Nikhil Gopal
  • 87
  • 2
  • 5
  • 11

8 Answers8

1
  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
Community
  • 1
  • 1
TheLostMind
  • 34,842
  • 11
  • 64
  • 97
  • I suppose it can be done using two String variables and two int counters, why to create unnecessary memory. – Shreyas Dave Feb 26 '14 at 09:09
  • @ShreyasDave- Suppose tomorrow he wants the character which has the third largest count .. and the day after that all characters with count greater than or equal to 5. Now, imagine the amount of code change the OP would have to do. It is always better to keep the design flexible so that the application can be improved with minimal code/design change.. – TheLostMind Feb 26 '14 at 09:16
1
    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
makata
  • 1,939
  • 2
  • 22
  • 20
1
  • 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.

Duong
  • 19
  • 2
0

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++;
    }
  }
}
SeeTheC
  • 1,492
  • 11
  • 13
0

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


}
}
Rahul
  • 3,401
  • 3
  • 13
  • 27
0

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

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
0

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.

Parth Srivastav
  • 316
  • 2
  • 13
0

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

Frakcool
  • 10,088
  • 9
  • 41
  • 71