簡體   English   中英

給定一個字符串作為輸入,返回出現在字符串中的最大次數的char

[英]Given a string as input, return the char which occurs the maximum number of times in the string

您可以假設最多只會出現1個字符。

         Input             |     Output  
---------------------------+--------------
mostFreq("hello")          |       l
mostFreq("1223334445555")  |       5
mostFreq("z")              |       z

public char mostFreq(String str){

      int count=0;
        String temp=""; // An empty string to keep track of counted
                       // characters
        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {
                char k=str.charAt(j);  
            // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }
             }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {    

            temp=temp+c; // append the character to the temp indicating
                        // that you have already counted it
             } 
             return c;
        }
        return 0;

   }

我正在嘗試運行以上代碼,但失敗了,請問任何建議嗎?

嘗試這個。

public char mostFreq(String str){

    int highestFreq = 0;

      char mostFreqChar = ' ';

      for (int i = 0; i < str.length(); i++)

      {

          //Get a char and go through entire string to determine how many times that char occurs

          char x = str.charAt(i);
          int c = 0;

          for (int j = str.indexOf(x); j != -1; j = str.indexOf(x, j + 1))

          {

              c++;

          }

          if (c > highestFreq)

          {

              highestFreq = c;

              mostFreqChar = x;
          }

      }

      return mostFreqChar;
}

為什么不使用Map並索引每個字符的出現? 我們可以做這樣的事情:

 public int mostFreq(String str){
     Map<Character, Integer> occurences = new HashMap<>();
     char[] characters = str.toCharArray();

     for (int i = 0; i < characters.length; i++) {
         if (occurences.get(characters[i]) == null)
             occurences.put(characters[i], 1)

         else {
             int amount = occurences.get(characters[i]);
             amount++;
             occurences.put(characters[i], amount);
         }
     }

     int max = 0;
     Iterator<Integer> iterator = occurences.keyset().iterator();

     while (iterator.hasNext()) {
         int next = iterator.next();

         if (next > max)
            max = next;


     }

     return next;


 }

將String轉換為char [],然后將每個char放入Hashmap中。 對於每個重復出現的字符,它都會增加計數器。 最后返回字符。

public char mostFreq(String str){
    Map<Character,Integer> occurences = new HashMap<Character, Integer>();
    Character mostFreq = null ;
    if (str !=null && str.length()>0){
        char[] chars = str.toCharArray();
        for(char c : chars){
            // increase occurences if exists
            if (occurences.containsKey(c)){
                occurences.put(c, occurences.get(c)+1);
            // create an entry if not
            }else{
                occurences.put(c, 1);
            }
        }
        // search for key with highest value
        int count = 0;
        for(Map.Entry<Character,Integer> entry : occurences.entrySet()){
            if (entry.getValue() > count){
                mostFreq = entry.getKey();
                count = entry.getValue();
            }
        }
    }
    return mostFreq;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM