我正在编写代码来读取字符串并计算重复组
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
如果我尝试输入 aabbcdaaaabb 我应该有 4 组重复小数 啊| BB |啊啊| BB
我知道我没有读取第一组 aa,因为我的索引从 1 开始。我尝试将其修复为读取零,但随后我尝试修复整个循环以处理更改,但我失败了,是吗?关于如何更改索引或循环有什么建议吗?
最佳答案
试试这个代码:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
编辑 - 将 aaaa 计为 4,固定为计为 1
关于java - 无法读取重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16101695/