更新抱歉,我误解了您的问题,您需要在代码中进行以下更改才能使其正常工作.(带注释的行)
public static int runLongestIndex(String setofletters){
int ctr = 1; // every character is repeated at least once, so you should initialize it to 1, not 0
int ctrstor = 0;
int ii = 0;
int output = 0;
for (int i = 0; i < setofletters.length() - 1; i++) {
if (i < setofletters.length() - 1 && setofletters.charAt(i) == setofletters.charAt(i+1)) { // i++ is not same as i+1
ctr++;
ii = i+1; // i++ is not same as i+1
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
ctrstor = ctr;
}
ctr = 1; // for the same reason I mentioned above
}
return output;
}
编辑:编写代码的最简单方法是:
public static int runLongestIndex(String setofletters){
int ctr = 1;
int output = 0;
int j=0;
for(int i=0; i
j=i;
while(i
i++;
ctr++;
}
if(ctr>output){
output=j;
}
ctr = 1;
}
return output;
}
为什么要将i分配给输出?您应该将ctr分配给输出.
更改
if(ctr>ctrstor){
output=i;
}
至
if(ctr>ctrstor){
output=ctr;
}
而且我认为你应该改变
if(setofletters.charAt(i)==setofletters.charAt(i++))
至
if(i
并且你应该将ctr初始化为1而不是0,因为每个字符至少重复一次.