gpt4 book ai didi

java - 计算字符串中连续重复出现的字符数

转载 作者:行者123 更新时间:2023-12-01 20:14:36 24 4
gpt4 key购买 nike

这是我的代码。

public static void countContinuosOccurence() {
String first = "ABBCDDDEFGGH";
StringBuffer result = new StringBuffer();
int count = 1;
for (int i = 1; i < first.length(); i++) {
if (first.charAt(i) == (first.charAt(i - 1))) {
count++;
} else {
if (count > 1) {

result.append(String.valueOf(count) + first.charAt(i - 1));
} else {
result.append(first.charAt(i - 1));
}
count = 1;
}
}
System.out.println("First String is:"+ first);
System.out.println("Result is:" + result);
}

结果是:

First String is:ABBCDDDEFGGH
Result is:A2BC3DEF2G

缺少最后一个字符?有人可以帮我解决这个问题吗?

最佳答案

不是性能最好的,但最简单的代码:

final String in = "ABBCDDDEFGGH" + '\u0000';
final StringBuilder b = new StringBuilder();
char prev = in.charAt(0);
int rpt = 0;
for (int i = 1; i < in.length(); i++) {
final char curr = in.charAt(i);
if (curr == prev) rpt++;
else {
b.append(rpt == 0? prev : "" + (rpt + 1) + prev);
rpt = 0; prev = curr;
}
}
System.out.println(b);

关于java - 计算字符串中连续重复出现的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10346304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com