如何使用Java查找字符串中最常出现的字符?

时间:2014-02-13 09:41:25

标签: java algorithm histogram

给定一个段落作为输入,找到最常出现的字符。请注意,角色的情况无关紧要。如果多个字符具有相同的最大出现频率,则返回所有字符 我正在尝试这个问题,但我什么都没有。以下是我尝试的代码,但它有很多我无法纠正的错误:

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

23 个答案:

答案 0 :(得分:3)

你已经在这里得到了答案:https://stackoverflow.com/a/21749133/1661864

这是我能想象到的最简单的方式。

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

答案 1 :(得分:3)

为什么不简单地使用N个字母桶(N =字母表中的字母数)?只需沿着字符串去增加相应的字母桶。时间复杂度O(n),空间复杂度O(N)

答案 2 :(得分:0)

如果您对 3rd 方库开放,则可以使用 Bag 中的 Eclipse Collections 类型并选择出现次数最多的内容。

public char[] maxOccurringChar(String s) {
    MutableCharBag bag = CharBags.mutable.of(s.toCharArray());
    MutableList<CharIntPair> maxOccurringCharsWithCounts = bag.topOccurrences(1);
    MutableCharList maxOccurringChars = maxOccurringCharsWithCounts.collectChar(CharIntPair::getOne);
    return maxOccurringChars.toArray();
}

请注意,在此示例中,我们使用原始集合来避免对 charint 类型进行装箱。

答案 3 :(得分:0)

./configure

在上面,我使用的是流。以下是步骤:

  1. 使用流将字符串的字符转换为数组列表。
  2. 使用在步骤 1 中创建的 arrayList 创建一个哈希集(丢弃所有重复出现的字符)。
  3. 使用 Collections.frequency 计算 arrayList 中每个字符的出现次数。
  4. 这不是最简单的解决方案,也不是很可爱!但是,它利用了流,这是我最近开始学习并想应用的东西。我不擅长使用流,但它们很漂亮。我已经在 stackoverflow 上学到了其中的大部分内容,我非常感激。 :)

答案 4 :(得分:0)

        import java.util.HashMap;
        import java.util.Map;
        import java.util.Set;
        import java.util.Map.Entry;

        public class Maxchar {

            public static void main(String[] args) {

                String str = "vaquar khan.";
                // System.out.println();
                System.out.println(maxChar(str));
                String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
                System.out.println(maxChar(testcase1));

            }

            private static char maxChar(String str) {

                if (null == str)
                    return ' ';

                char[] charArray = str.replaceAll("\s+", "").toCharArray();
                //

                Map<Character, Integer> maxcharmap = new HashMap<Character, Integer>();
                //
                for (char c : charArray) {
                    if (maxcharmap.containsKey(c)) {
                        maxcharmap.put(c, maxcharmap.get(c) + 1);
                    } else {
                        maxcharmap.put(c, 1);
                    }
                    // Inside map we have word count
                    // System.out.println(maxcharmap.toString());
                }

                //
                //

                Set<Entry<Character, Integer>> entrySet = maxcharmap.entrySet();
                int count = 0;
                char maxChar = 0;
                //
                for (Entry<Character, Integer> entry : entrySet) {
                    if (entry.getValue() > count) {
                        count = entry.getValue();
                        maxChar = entry.getKey();
                    }
                }

                System.out.println("Maximum Occurring char and its count :");
                System.out.println(maxChar + " : " + count);

                return maxChar;
            }

        }

答案 5 :(得分:0)

尽管所有答案都是正确的,但我的发布方式仍然如此

/ 问题:对于给定的字符串(例如“ aabbbbbcc”),打印出现时间最长的字符, 索引及其发生的次数。 例如: “出现时间最长的字符是b,索引2的长度是5”。 /

class Codechef {
public static void main (String[] args) {
    String problem = "aabbbbbcc";
    Map<Character,Temp> map = new HashMap<>();
    for(int i = 0; i < problem.length(); i++){
  if (map.containsKey(problem.charAt(i))) {
    map.get(problem.charAt(i)).incrementCount();
  } else {
    map.put(problem.charAt(i), new Temp(i, 1, problem.charAt(i)));
  }
    }

    List<Map.Entry<Character, Temp>> listOfValue = new LinkedList<Map.Entry<Character, Temp>>(map.entrySet());
    Comparator<Map.Entry<Character, Temp>> comp = (val1, val2) -> (val1.getValue().getCount() < val2.getValue().getCount() ? 1: -1);
    Collections.sort(listOfValue, comp);
    Temp tmp = listOfValue.get(0).getValue();
    System.out.println("longest occurring character is "+ tmp.getStr()+ " and length is " + tmp.getCount()+ " at index "+ tmp.getIndex());

}}

然后创建一个Model类以保留这些值

class Temp {
Integer index;
Integer count;
Character str;
public Temp(Integer index, Integer count, Character str ){
    this.index = index;
    this.count = count;
    this.str = str;
}
public void incrementCount(){
    this.count++;
}
public Integer getCount(){
    return count;
}
public Character getStr(){
    return str;
}
public Integer getIndex(){
    return index;
}}

答案 6 :(得分:0)

此处 str 将是给定的字符串。这是Javascript代码

function maxCharacter(str){
let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
    reptCharsCount=0;
    for(let j=0; j< str1.length; j++){
        if(str1[i] === str1[j]) {
            reptCharsCount++;
        }
    }

    if(reptCharsCount > maxCount) {
        ele = str1[i];
        maxCount = reptCharsCount; 
    }
}
return ele;

}

答案 7 :(得分:0)

我看到许多不必要的答案,例如进口大量物品或使用大炮射击蚊子(公认的答案使用HashTable)。

这是一个简单的解决方案:

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

答案 8 :(得分:0)

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

答案 9 :(得分:0)

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

}

答案 10 :(得分:0)

问题:字符串中经常出现的字符

方法1:使用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

    }
}

方法2:在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
}

方法3:使用collections.Counter()。most_common()

import collections


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

方法4:使用sorted和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)   

答案 11 :(得分:0)

此方法允许您在字符串中查找最常出现的字符:

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

答案 12 :(得分:0)

尝试那样: -

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

答案 13 :(得分:0)

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

}

答案 14 :(得分:0)

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

答案 15 :(得分:0)

对于简单字符串操作,此程序可以完成:

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

示例输入1:Pratik是一位优秀的程序员

示例输出1:最大出现次数为3的字符a

示例输入2:hello WORLD

示例输出2:最大出现次数是字符l

的3

答案 16 :(得分:0)

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

答案 17 :(得分:0)

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

答案 18 :(得分:0)

另一种解决方法。一个更简单的。

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;

}

答案 19 :(得分:0)

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

答案 20 :(得分:0)

以下解决方案的大O只是o(n)。请分享您的意见。

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

                }

            }

        }

    }

答案 21 :(得分:0)

算法: -

  1. 将字符串字符按字符复制到LinkedHashMap。

    • 如果是新角色,则插入新角色,1。
    • 如果LinkedHashMap中已存在字符,则通过递增1来更新该值。
  2. 逐个迭代该条目并将其存储在Entry对象中。

    • 如果条目对象中存储的密钥值大于或等于当前条目,则不执行任何操作
    • 否则,在Entry对象中存储新条目
  3. 循环后,只需从Entry对象中打印键和值。

  4. 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");
    }
    

    }

答案 22 :(得分:0)

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;

   }
   }