How to find the most frequently occurring character in a string with Java?

ⅰ亾dé卋堺 提交于 2020-05-09 06:25:30

问题


Given a paragraph as input, find the most frequently occurring character. Note that the case of the character does not matter. If more than one character has the same maximum occurring frequency, return all of them I was trying this question but I ended up with nothing. Following is the code that I tried but it has many errors I am unable to correct:

public class MaximumOccuringChar {

    static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";

    public static void main(String[] args) 
    {
        MaximumOccuringChar test = new MaximumOccuringChar();
        char[] result = test.maximumOccuringChar(testcase1);
        System.out.println(result);
    }

    public char[] maximumOccuringChar(String str) 
    {
        int temp = 0;
        int count = 0;
        int current = 0;

        char[] maxchar = new char[str.length()];

        for (int i = 0; i < str.length(); i++) 
        {
            char ch = str.charAt(i);

            for (int j = i + 1; j < str.length(); j++) 
            {
                char ch1 = str.charAt(j);

                if (ch != ch1) 
                {
                    count++;
                }
            }

            if (count > temp) 
            {
                temp = count;
                maxchar[current] = ch;
                current++;
            }
        }
        return maxchar;
    }
}

回答1:


You already got your answer here: https://stackoverflow.com/a/21749133/1661864

It's a most easy way I can imagine.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MaximumOccurringChar {

    static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";


    public static void main(String[] args) {
        MaximumOccurringChar test = new MaximumOccurringChar();
        List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
        System.out.println(result);
    }


    public List<Character> maximumOccurringChars(String str) {
        return maximumOccurringChars(str, false);
    }

    // set skipSpaces true if you want to skip spaces
    public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
        Map<Character, Integer> map = new HashMap<>();
        List<Character> occurrences = new ArrayList<>();
        int maxOccurring = 0;

        // creates map of all characters
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (skipSpaces && ch == ' ')      // skips spaces if needed
                continue;

            if (map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            } else {
                map.put(ch, 1);
            }

            if (map.get(ch) > maxOccurring) {
                maxOccurring = map.get(ch);         // saves max occurring
            }
        }

        // finds all characters with maxOccurring and adds it to occurrences List
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if (entry.getValue() == maxOccurring) {
                occurrences.add(entry.getKey());
            }
        }

        return occurrences;
    }
}



回答2:


Why don't you simply use N letter buckets (N=number of letters in alphabet) ? Just go along the string and increment the corresponding letter bucket. Time complexity O(n), space complexity O(N)




回答3:


import java.util.Scanner;

public class MaximumOccurringChar{

static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";

public static void main(String[] args) {
    MaximumOccurringChar test = new MaximumOccurringChar();
   String result = test.maximumOccuringChar(testcase1);
    System.out.println(result);
}

public String maximumOccuringChar(String str) {
    int temp = 0;
    int count = 0;
    int current = 0;
    int ind = 0;
    char[] arrayChar = {'a','b' , 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    int[] numChar = new int[26];
    char ch;
    String s="";
    str = str.toLowerCase();
    for (int i = 0; i < 26; i++) {
        count = 0;
        for (int j = 0; j < str.length(); j++) {
            ch = str.charAt(j);
            if (arrayChar[i] == ch) {
                count++;
            }
        }
        numChar[i] = count++;
    }
    temp = numChar[0];

    for (int i = 1; i < numChar.length; i++) {
        if (temp < numChar[i]) {
            temp = numChar[i];

            ind = i;
            break;
        }
    }
       System.out.println(numChar.toString());
        for(int c=0;c<26;c++)
        {
            if(numChar[c]==temp)
            s+=arrayChar[c]+" ";


        }


    return s;

   }
   }



回答4:


Algorithm:-

  1. Copying the String character by character to LinkedHashMap.

    • If its a new character then insert new character , 1.
    • If character is already present in the LinkedHashMap then update the value by incrementing by 1.
  2. Iterating over the entry one by one and storing it in a Entry object.

    • If value of key stored in entry object is greater than or equal to current entry then do nothing
    • Else, store new entry in the Entry object
  3. After looping through, simply print the key and value from Entry object.

public class Characterop {

public void maxOccur(String ip)
{

    LinkedHashMap<Character, Integer> hash = new LinkedHashMap();
    for(int i = 0; i<ip.length();i++)
    {
        char ch = ip.charAt(i);
        if(hash.containsKey(ch))
        {
            hash.put(ch, (hash.get(ch)+1));

        }
        else
        {
            hash.put(ch, 1);
        }
    }

   //Set set = hash.entrySet();
   Entry<Character, Integer> maxEntry = null;
   for(Entry<Character,Integer> entry : hash.entrySet())
   {
      if(maxEntry == null)
      {
          maxEntry = entry;
      }

      else if(maxEntry.getValue() < entry.getValue())
      {
          maxEntry = entry;
      }
   }
    System.out.println(maxEntry.getKey());


}
public static void main(String[] args) {
    Characterop op = new Characterop();
    op.maxOccur("AABBBCCCCDDDDDDDDDD");
}

}




回答5:


The Big O below solution is just o(n). Please share your opinion on it.

    public class MaxOccuringCahrsInStr {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String str = "This is Sarthak Gupta";

            printMaxOccuringChars(str);

        }

        static void printMaxOccuringChars(String str) {
            char[] arr = str.toCharArray();
            /* Assuming all characters are ascii */
            int[] arr1 = new int[256];
            int maxoccuring = 0;

            for (int i = 0; i < arr.length; i++) {
                if (arr[i] != ' ') { // ignoring space
                    int val = (int) arr[i];
                    arr1[val]++;
                    if (arr1[val] > maxoccuring) {
                        maxoccuring = arr1[val];
                    }
                }

            }

            for (int k = 0; k < arr1.length; k++) {
                if (maxoccuring == arr1[k]) {
                    char c = (char) k;
                    System.out.print(c + " ");

                }

            }

        }

    }



回答6:


function countString(ss)
        {
            var maxChar='';
            var maxCount=0;
            for(var i=0;i<ss.length;i++)
            {
                var charCount=0;
                var localChar=''
                for(var j=i+1;j<ss.length;j++)
                {
                    if(ss[i]!=' ' && ss[i] !=maxChar)
                    if(ss[i]==ss[j])
                    {
                        localChar=ss[i];
                        ++charCount;
                    }
                }
                if(charCount>maxCount)
                {
                    maxCount=charCount;
                    maxChar=localChar;
                }
            }
            alert(maxCount+""+maxChar)
        }



回答7:


Another way to solve it. A simpler one.

public static void main(String[] args) {

    String str= "aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcddddeeeeee";
    String str1 = "dbc";

    if(highestOccuredChar(str) != ' ')
    System.out.println("Most Frequently occured Character ==>  " +Character.toString(highestOccuredChar(str)));
    else
        System.out.println("The String doesn't have any character whose occurance is more than 1");
}

private static char highestOccuredChar(String str) {

    int [] count = new int [256];

    for ( int i=0 ;i<str.length() ; i++){
        count[str.charAt(i)]++;
    }

    int max = -1 ;
    char result = ' ' ;

    for(int j =0 ;j<str.length() ; j++){
        if(max < count[str.charAt(j)] && count[str.charAt(j)] > 1) {
            max = count[str.charAt(j)];
            result = str.charAt(j);
        }
    }

    return result;

}



回答8:


public void countOccurrence(String str){
    int length = str.length();
    char[] arr = str.toCharArray();
    HashMap<Character, Integer> map = new HashMap<>();
    int max = 0;

    for (char ch : arr) {
        if(ch == ' '){
            continue;
        }
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    Set<Character> set = map.keySet();

    for (char c : set) {
        if (max == 0 || map.get(c) > max) {
            max = map.get(c);
        }
    }

    for (Character o : map.keySet()) {
        if (map.get(o).equals(max)) {
            System.out.println(o);
        }
    }
    System.out.println("");
}

public static void main(String[] args) {
    HighestOccurence ho = new HighestOccurence();

    ho.countOccurrence("aabbbcde");
}



回答9:


public void stringMostFrequentCharacter() {
    String str = "My string lekdcd dljklskjffslk akdjfjdkjs skdjlaldkjfl;ak adkj;kfjflakj alkj;ljsfo^wiorufoi$*#&$ *******";
    char[] chars = str.toCharArray(); //optionally - str.toLowerCase().toCharArray();
    int unicodeMaxValue = 65535;    // 4 bytes
    int[] charCodes = new int[unicodeMaxValue];
    for (char c: chars) {
        charCodes[(int)c]++;
    }
    int maxValue = 0;
    int maxIndex = 0;
    for (int i = 0; i < unicodeMaxValue; i++) {
        if (charCodes[i] > maxValue) {
            maxValue = charCodes[i];
            maxIndex = i;
        }
    }
    char maxChar = (char)maxIndex;
    System.out.println("The most frequent character is >" + maxChar + "<  -  # of times: " + maxValue);
}



回答10:


For Simple String Manipulation, this program can be done as:

package abc;
import java.io.*;

public class highocc 
{
        public static void main(String args[])throws IOException
        {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter any word : ");
            String str=in.readLine();
            str=str.toLowerCase();
            int g=0,count,max=0;;
            int ar[]=new int[26];
            char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
                for(int i=0;i<ch.length;i++)
                {
                    count=0;
                    for(int j=0;j<str.length();j++)
                     {
                        char ch1=str.charAt(j);
                        if(ch[i]==ch1)
                            count++;
                     }
                   ar[i]=(int) count;
                }
                max=ar[0];
                for(int j=1;j<26;j++)
                {
                    if(max<ar[j])
                        {
                            max=ar[j];
                            g=j;
                        }
                }
                System.out.println("Maximum Occurence is "+max+" of character "+ch[g]);
           } 
}

Sample Input1: Pratik is a good Programmer

Sample Output1: Maximum Occurence is 3 of character a

Sample Input2: hello WORLD

Sample Output2: Maximum Occurence is 3 of character l




回答11:


maxOccu m = new maxOccu();
String str = "moinnnnaaooooo";
char[] chars = str.toCharArray();
Arrays.sort(chars);
str = new String(chars);
System.out.println(str);
m.maxOccurence(str);

void maxOccurence(String str) {
    char max_char = str.charAt(0),
    cur_char,
    prev = str.charAt(0);
    int cur_count = 0,
    max_count = 0,
    n;
    n = str.length();
    for (int i = 0; i < n; i++) {
        cur_char = str.charAt(i);
        if (cur_char != prev) cur_count = 0;
        if (str.charAt(i) == cur_char) {
            cur_count++;
        }
        if (cur_count > max_count) {
            max_count = cur_count;
            max_char = cur_char;
        }
        prev = cur_char;
    }
    System.out.println(max_count + "" + max_char);
}



回答12:


public class HigestOccurredCharTest {

    public static void main(String[] args) {
        System.out.println("Enter the char string to check higest occurrence");
        Scanner scan = new Scanner(System.in);
        String str = scan.next();
        if(str != null && !str.isEmpty()){
            Map<Character, Integer> map = countOccurrence(str);
            getHigestOccurrenceChar(map);
        }else{
            System.out.println("enter valid string");
        }
    }

    public static Map<Character, Integer> countOccurrence(String str){
         char strArr[] = str.toCharArray();
         Map<Character, Integer> map = new HashMap<Character , Integer>();
         for (Character ch : strArr) {
            if(map.containsKey(ch)){
                map.put(ch, map.get(ch)+1);
            }else{
                map.put(ch, 1);
            }
        }
        return map;
    }

    public static void getHigestOccurrenceChar(Map<Character, Integer> map){
        Character ch = null;
        Integer no = 0;
         Set<Entry<Character, Integer>> entrySet = map.entrySet();
         for (Entry<Character, Integer> entry : entrySet) {
             if(no != 0 && ch != null){
                 if(entry.getValue() > no){
                     no = entry.getValue();
                     ch = entry.getKey();
                 }
             }else{
                 no = entry.getValue();
                  ch = entry.getKey();
             }


        }
         System.out.println(ch+ " Higest occurrence char is "+ no);
    }

}



回答13:


Try Like that:-

        string inputString = "COMMECEMENT";
        List<Tuple<char, int>> allCharListWithLength = new List<Tuple<char, int>>();
        List<char> distinchtCharList = inputString.Select(r => r).Distinct().ToList();
        for (int i = 0; i < distinchtCharList.Count; i++)
        {
            allCharListWithLength.Add(new Tuple<char, int>(distinchtCharList[i], inputString.Where(r => r ==
            distinchtCharList[i]).Count()));
        }
        Tuple<char, int> charWithMaxLength = allCharListWithLength.Where(r => r.Item2 == allCharListWithLength.Max(x => x.Item2)).FirstOrDefault();



回答14:


This method allows you to find the most frequently occurring character in a string:

  public char maximumOccuringChar(String str) {
    return str.chars()
            .mapToObj(x -> (char) x)                  // box to Character
            .collect(groupingBy(x -> x, counting()))  // collect to Map<Character, Long>
            .entrySet().stream()
            .max(comparingByValue())                  // find entry with largest count
            .get()                                    // or throw if source string is empty
            .getKey();
}



回答15:


Question: Frequently occurring Character in a String

Method 1: Using HashMap

public class t1{

    public static void main(String a[]){
Map<Character, Integer> map = new HashMap<>();
String a1 = "GiinnniiiiGiiinnnnnaaaProtijayi";
 for(char ch : a1.toCharArray()) {map.put(ch, map.getOrDefault(ch,0)+1);}//for
        System.out.println(map);

 char maxchar = 0 ;
 int maxvalue = Collections.max(map.values());
 System.out.println("maxvalue => " + maxvalue);
 for(   Entry<Character,Integer> entry  : map.entrySet()) {
     if(entry.getValue() == maxvalue) {

         System.out.println("most frequent Character => " + entry.getKey());
     }
 }//for

    }
}

Method 2 : Using count of alphabets in Python

str = "GiinnniiiiGiiinnnnnaaaProtijayi";

count = [0]*256
maxcount= -1
longestcharacter ="" 

    # Traversing through the string and maintaining the count of
    # each character
for ch in str:count[ord(ch)] += 1;

for ch in str:
    if( maxcount < count[ord(ch)] ):
        maxcount = count[ord(ch)]
        longestcharacter = ch


print(longestcharacter) 
print(maxcount) 

IN Java :

public class t1{

   public static void main(String[] args) {
     String  a = "GiinnniiiiGiiinnnnnaaaProtijayi";
     int[] count = new int[256];
     for (int i = 0; i < a.length(); i++) {
        char ch = a.charAt(i);
        count[ch] +=1;
    }//for

     int maxcount = -1 ;
     char longest = 0 ;
     for( char ch : a.toCharArray()) {
         if(count[ch] > maxcount) {
              maxcount = count[ch];
              longest = ch ;
         }//if

     }//for
     System.out.println(longest);
     System.out.println(maxcount);



}//main
}

Method 3: Using collections.Counter().most_common()

import collections


a = "GiinnniiiiGiiinnnnnaaaProtijayi";
fullDictionary = collections.Counter(a).most_common()
FirstElementWithCount = fullDictionary[0]
print(FirstElementWithCount)
FirstElementWithoutCount = FirstElementWithCount[0]
print(FirstElementWithoutCount)

Method 4: Using sorted and key = lambda ch : ch[1]

a = "GiinnniiiiGiiinnnnnaaaProtijayi";

d = {}

for ch in a: d[ch] = d.get(ch, 0) + 1
fullDictionary = sorted(d.items(), key=lambda ch :ch[1], reverse=True)

print(fullDictionary)

FirstElement = fullDictionary[0][0]
print(FirstElement)   



回答16:


package com.practice.ArunS;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class HighestFrequencyElement {
    /*
     * CONTENTSERV=N(2),T(2),E(2) SearchSort=S(2),r(2)
     * HighestFrequencyElement=E(5)
     */
    public static void main(String[] args) {
        String str = "CONTENTSERV";
        findHighestFrequencyElement(str);

    }

    private static void findHighestFrequencyElement(String str) {
        System.out.println("Original String:" + str);
        Map<String, Integer> myMap = new TreeMap<String, Integer>();

        char[] ch = str.toCharArray();
        for (int i = 0; i < str.length(); i++) {
            if (myMap.containsKey(Character.toString(ch[i]))) {
                Integer value = myMap.get(Character.toString(ch[i]));
                myMap.replace(Character.toString(ch[i]), ++value);
            } else {
                myMap.put(Character.toString(ch[i]), 1);
            }
        } // end of foor loop

        Comparator<Entry<String, Integer>> valueComparator = new Comparator<Entry<String, Integer>>() {

            @Override
            public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
                Integer v1 = e1.getValue();
                Integer v2 = e2.getValue();
                return v2-v1;
            }
        };

        // Sort method needs a List, so let's first convert Set to List in Java
        List<Entry<String, Integer>> listOfEntries = new ArrayList<Entry<String, Integer>>(myMap.entrySet());

        // sorting HashMap by values using comparator
        Collections.sort(listOfEntries, valueComparator);
        for(int i=0;i<listOfEntries.size();i++){
            if(listOfEntries.get(0).getValue()==listOfEntries.get(i).getValue()){
                System.out.println(listOfEntries.get(i));
            }
        }

    }//end of method

}



回答17:


    import java.util.Arrays;
    import java.util.Collections;

    import java.util.Comparator;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;

public class Answers {
    public static void main(String[] args) {
        String input1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
        String[] arin = input1.split("");
        Predicate<String> checkIfValidChar = str -> ((str.charAt(0) >= '0' && str.charAt(0) <= '9')
                || (str.charAt(0) >= 'a' && str.charAt(0) <= 'z')
                || (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z'));
        String maxChar = Arrays.stream(arin).max(Comparator.comparing(i -> Arrays.stream(arin).filter(j -> {
            return i.equalsIgnoreCase(j) && checkIfValidChar.test(j);
        }).count())).get();

        int count = Collections.frequency(Arrays.asList(arin), maxChar);
        System.out.println(Arrays.stream(arin).filter(i -> {
            return Collections.frequency(Arrays.asList(arin), i) == count && checkIfValidChar.test(i);
        }).collect(Collectors.toSet()));
    }
}



回答18:


I see many answers that are unnecessarily convoluted, import tons of stuff or use a cannon to shoot a mosquito ( the accepted answer uses an HashTable ).

Here a simple solution:

public List<Character> mostFrequentLetter(String message) {
  var m = message
      .replaceAll("[^a-z]", "")
      .toLowerCase();

  int[] count = new int[26]; 
  for(var c : m.toCharArray()){
    int i = ((int)c)-97;
    count[i]++;
  }
  var max_i = 0; // index of the most frequent letter
  var max_c = count[max_i]; // count of the most frequent letter
  var max = new ArrayList<Character>(3); // list containing letters with the same frequency
  for(int i = 1; i < 26; ++i){
    if (count[i] >= max_c){
      max_i = i;
      char c = (char)(max_i + 97);
      if(count[i]!=max_c){
        max.clear();
        max_c = count[i];
      }
      max.add(c);
    }
  }
  return max;
}


来源:https://stackoverflow.com/questions/21750365/how-to-find-the-most-frequently-occurring-character-in-a-string-with-java

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