计算字符串中 char 的多个实例(连续)

counting multiple instances of a char (in a row) in a string

不知道为什么我的代码不起作用。它一直返回值 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;
}  
}

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

你想要这个:

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

而不是:

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

然后在你 return 之前的末尾添加:

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

我看到 3 个问题。

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

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

在循环之外,您需要进行最终检查以查看最后一个字符序列是否具有最高分。 if(count > 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;