Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我需要在下面的代码中使用count-=1?_Java - Fatal编程技术网

Java 为什么我需要在下面的代码中使用count-=1?

Java 为什么我需要在下面的代码中使用count-=1?,java,Java,当创建下面的函数时,为了得到正确的答案,我必须添加count-=1行,否则答案会偏移1 public int countCTG(String dna) { int count = 0; int firstOccurrence = dna.indexOf("CTG"); if (firstOccurrence != -1) { count +=1; while (dna.indexOf("CTG", firstOccurrence) !=

当创建下面的函数时,为了得到正确的答案,我必须添加count-=1行,否则答案会偏移1

public int countCTG(String dna) {
    int count = 0;
    int firstOccurrence = dna.indexOf("CTG");

    if (firstOccurrence != -1) {
        count +=1;
        while (dna.indexOf("CTG", firstOccurrence) != -1 && firstOccurrence != -1) {
            count +=1;
            firstOccurrence = dna.indexOf("CTG", firstOccurrence+3);
        }
        count -=1;
    }
    else {
        count = 0;
    }
    return count;
}
我设法让这个函数工作,但是你能帮我理解它背后的逻辑吗?count变量最初初始化为0,例如,如果字符串包含一个CTG实例,则它将通过count+=1行进行计数。count-=1是否将此变量重置回0?

因为您在第一次搜索后没有更新firstOccurrence,即从开始搜索两次。在开始从以前的结果搜索之前,indexOfCTG。indexOfCTG,prevResultIndex+3

还请注意:

在while循环之前不必搜索一次 else子句是多余的 你在打电话。indexOf是你实际需要的两倍 第一次出现+3是一种负担,当字符串更改时,您将忘记更新偏移量,这将很难跟踪。将搜索到的字符串存储在一个位置,并计算其长度,而不是对其进行硬编码。
编辑:嗯@AndyTurner为您重新编写了它,但请尝试查看列出的每一个点是如何达到该结果的

您需要-1,因为循环之前有+1:while循环的第一次迭代再次计算已找到的事件

更简单的解决方案如下:

int count = 0;
int skip = "CTG".length();
int current = -skip;
while ((current = dna.indexOf("CTG", current + skip)) >= 0) {
  ++count;
}
return count;