【问题标题】:counting multiple instances of a char (in a row) in a string [closed]计算字符串中字符的多个实例(连续)[关闭]
【发布时间】:2016-10-12 19:23:51
【问题描述】:

不知道为什么我的代码不起作用。它不断返回值 1 而不是我期望的值。

public class Lab5Example
{
  public static void main(String[] args)
  {
  System.out.println(longestRun("aabbbccd"));
  System.out.println("Expected 3");
  System.out.println(longestRun("aaa"));
  System.out.println("Expected 3");
  System.out.println(longestRun("aabbbb"));
  System.out.println("Expected 4");
  }


public static int longestRun(String s)
{
int count = 1;
int max = 1;

for (int i = 0; i < s.length() - 1; i += 1) {
  char c = s.charAt(i);
  char current = s.charAt(i + 1);
  if (c == current) {
    count += 1;
  }
  else {
    if (count > max) {
      count = max;
    }
    current = c;       
  }
}
return max;
}  
}

调试器工作不正常,所以我不知道什么不工作。

【问题讨论】:

  • 为什么你认为调试器不工作?
  • 你将max初始化为1,永远不要修改,然后返回;除了1,它不能返回任何东西。
  • 看起来像是没有正确设置 max 的组合(根本),而且 count 需要在某个时候重置,否则您将连续计算所有重复字符而不是计数连续给定字符的最长序列。
  • @ScottHunter 我打了一些东西(一个选项或其他什么)并检查了一切,但无论如何,一旦我点击调试(对于我编写的任何代码),它不允许我完成这些步骤。 @resueman 是的,我发现了,将 count = max 转为 max = count

标签: java loops iteration counter


【解决方案1】:

我看到了 3 个问题。

max = count 应该是 count = max。这样您就可以存储迄今为止找到的最高分数。

current = c 应该是count = 1。这样您就可以重置计数以在下一个字符序列上重新开始计数。

在您的循环之外,您需要进行最后一次检查以查看最后一个字符序列是否得分最高。 if(count &gt; max) max = count;

这一切看起来像:

for (int i = 0; i < s.length() - 1; i += 1) {
    char c = s.charAt(i);
    char current = s.charAt(i + 1);
    if (c == current) {
        count += 1;
    }
    else {
        if (count > max) {
            max = count; // #1
        }
        count = 1; // #2
    }
}
if(count > max) // #3
    max = count;

return max;

【讨论】:

  • 是的,我在发布哈哈后立即抓住了count = max bs,但我完全忘记了重置。绝对需要让我的调试器再次弄清楚。感谢您的帮助。
  • 没问题,很高兴为您提供帮助。不需要current = c,因为字符将在下一次循环迭代中设置。
【解决方案2】:

你想要这个:

if (count > max) {
  max = count;
}

代替:

if (count > max) {
  count = max;
}

然后在您返回之前添加以下内容:

if(count > max)
{
    max = count;
}
return max;

【讨论】:

  • 即便如此,这仍然只有在最长的运行不在字符串末尾时才有效。 max 只会在找到新字母时设置。 count 现在也不会被重置。
  • 谁投了反对票?至少在您投反对票时说出原因...如果您不这样做,那么反对票对发帖人有何帮助?...
  • 关于编辑,我认为if (max == 1) 应该是另一个if (count &gt; max),以防万一它是一个更长的字符串,有多个运行。顺便说一句,DV 不是我
  • @jonhopkins 是的,你的权利......
猜你喜欢
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
相关资源
最近更新 更多