java - 最长运行计数程序问题

标签 java arrays for-loop

循环遍历 a 的 char 数组。程序应该找到给定字符的最长运行时间。

我遇到的问题是我总是错过 1 个数字,或者至少在这个例子中是这样。

我使用最常见的 for 循环与 a[i]==ch && a[i+1]==ch 来比较两个数字,如果找到匹配,我会在有 3 个连续字符的实例中执行 count++只给我 2,因为它与 i+1 进行比较。

我知道我不能做 a[i]==char 因为它不能作为程序的目的。

有人可以帮助我如何获得第三个计数吗?
我缺少这里的逻辑或其他东西。

    char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
    char ch = 'a';
    int count = 0;
    int oneTime = 0;

    for(int i = 0; i<a.length; i++){
        System.out.print(a[i]);
        System.out.print(" ");
    }

    System.out.println(" ");

    for(int i = 0; i<a.length-1; i++){



        if(a[i]==ch && a[i+1]==ch){
            count++;

        }//end of if
        if(oneTime ==0)
            if(a[a.length-2]==a[a.length-1]){
                count++;
                oneTime++;
            }

    }

    System.out.print(count);

}

}

最佳答案

计算比较而不是字符的标准错误。一次处理每个字符,并在它与您要查找的指定字符匹配时递增。

char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
char ch = 'a';

for(int i = 0; i<a.length; i++){
    System.out.print(a[i]);
    System.out.print(" ");
}

System.out.println(" ");

int count = 0;
int largest = 0;
for(int i = 0; i<a.length; i++){

    if(a[i]==ch){
        count++;
    }
    else {
        count = 0;
    }
    //now remember if this is the longest span
    if (count > largest) {
        largest = count;
    }
}

System.out.print("The longest run is: "+largest);

上面将找到指定字符的最长运行。

如果您想找到任意字符的最长连续串,请尝试以下操作:

char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
for(int i = 0; i<a.length; i++){
    System.out.print(a[i]);
    System.out.print(" ");
}

System.out.println(" ");

char ch = a[0];
int count = 1;
int largest = 1;
//note we skip the first character
for(int i = 1; i<a.length; i++){

    if(a[i]==ch){
        count++;
    }
    else {
        //reset with this char as first of a new run
        ch = a[i];
        count = 1;
    }
    //now remember if this is the longest span
    if (count > largest) {
        largest = count;
    }
}

System.out.print("The longest run is: "+largest);

关于java - 最长运行计数程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306802/

相关文章:

java - 如何更新存储图像的 JLabel

java - 如何使用 Drupal 或 Drupal 插件从 Java 应用程序中删除/替换 Alfresco?

java - 处理非递减的颜色亮度序列

javascript - 如何使用 es6 展平嵌套对象数组

javascript - Java 中的 map 集合

java - 通过比较两个参数打印连续的数字

java - 如何在不打开浏览器的情况下从提供的 URL 获取结果 [Php 代码/AJAX]

java - JPopupMenu 行为

javascript for 不工作

java - 用 Java 制作动画