java 最长序列_java – 查找字符串中相同字符的最长序列

本文介绍如何在Java中找到字符串中相同字符的最长连续序列。提供了两种不同的代码实现,通过比较字符来跟踪计数器,并更新最长序列的位置和长度。注意在代码中初始化计数器为1,因为每个字符至少重复一次,以及修正了循环条件和变量赋值的问题。
摘要由CSDN通过智能技术生成

更新抱歉,我误解了您的问题,您需要在代码中进行以下更改才能使其正常工作.(带注释的行)

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,因为每个字符至少重复一次.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值