【问题标题】:How do you get the max value to be the return?你如何获得最大值作为回报?
【发布时间】:2016-03-04 19:31:31
【问题描述】:

我或多或少地完成了我的代码,它适用于大多数字母组合。只有当我输入“iiiaa”之类的内容时它才会失败。它返回“a”出现次数最多,但“aaaii”之类的返回“a”也是最多的。我认为这个问题与某种数值有关,因为如果我列出字母 2 次或更多次后跟字母“a”,就会出现问题。 我目前的代码是:

  public static char most_frequent_character(String text)
{
int max_counter = 0;
char max_char = 'a';

for (int i = 1; i < text.length(); i++)
{
  char current = text.charAt(i);
  int counter = count_occurrences(text, current);

  char other_char = text.charAt(i-1);
  if (counter>count_occurrences(text, other_char))
  {
      max_char = current;

  }

}
return max_char;
}

count_occurrences 返回字母在单词中出现的次数

【问题讨论】:

  • 我收回我所说的这可能是一个价值问题。我认为这与以 'a' 开头的 char max_char 有关
  • 对您尝试解决的问题的解释会很有用。
  • if counter > max_counter 然后在 if 中设置 max_counter 就可以了。
  • 你的逻辑错了。您只需将当前字符的出现次数与前一个字符的出现次数进行比较,而不是将其与 all 字符的出现次数进行比较。使用一个Map,然后找到map中值最大的key。
  • @JBNizet 也打败了我。你应该遍历他的字母并制作一个字母和计数的地图,然后找到该地图中最大的。

标签: java if-statement for-loop max frequency


【解决方案1】:

if (counter&gt;count_occurrences(text, other_char)) 条件是错误的,因为如果当前字符的出现次数多于前一个字符,则它确定当前字符是出现次数最多的字符。您应该将其与当前的最大出现次数进行比较。您已经有一个 max_counter 变量来维持当前的最大出现次数。你应该使用它。并且循环的索引应该从 0 开始。

int max_counter = 0;
char max_char = 'a';

for (int i = 0; i < text.length(); i++)
{
  char current = text.charAt(i);
  int counter = count_occurrences(text, current);

  if (counter>max_counter)
  {
      max_char = current;
      max_counter = counter; 
  }

}
return max_char;

【讨论】:

    【解决方案2】:

    这可能对你有帮助 我们通过它的索引来决定每个字符。并迭代 for 循环,直到检查完每个字符。之后迭代直到列表大小并获得最大出现次数。

    public static char most_frequent_character(String text)
    {
        List<Integer> t = new ArrayList<Integer>();
        List<Character> t2 = new ArrayList<Character>();
        //int max_counter = 0;
        //char max_char = 'a';
        boolean updated = false;
        int indexForChar =0;
        for (int i = 0; i < text.length(); i++)
        {
            char other_char = text.charAt(i);
            if(t.size()>0)
            for(int j=0;j<t.size();j++)
            {
                if(other_char == t2.get(j))
                {
                    t.set(j, t.get(j)+1);
                    updated = true;
                    indexForChar--;
                    break;
                }
            }
    
            if(!updated)
            {
                t.add(1);
                t2.add(indexForChar, other_char);
            }
            updated = false;
            indexForChar++;
        }
        int max = 0;
        int index = 0;
        for(int j=0;j<t.size();j++)
        {
            if(max<t.get(j))
            {
                max = t.get(j);
                index= j;
            }
        }
        return t2.get(index);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 2022-07-29
      • 2011-07-05
      • 1970-01-01
      • 2022-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多