繁体   English   中英

查找字符串中连续重复字符的最大数目

[英]Find the max number of contiguous duplicated characters in a String

我需要代码的更新版本,该版本可以返回字符串中连续重复字符的最大数量,例如,在我们输入字符串"aabbbcccccd"的情况下, 结果应为5,因为我们有5 c

我的代码的问题是它将返回4

请注意,在我们有输入“ abccbbb ”的情况下,结果应该是3而不是4,因为字符串包含3个连续的重复字符(c)。

private int countRepeatedChars(String password)
{
    int maxNumberofRepeatedChars = 0;
    int counterOfSameChar = 0;
    boolean foundMoreThanOneChar = false;

    char ch, nextCh;
    for (int i = 0; i < password.length()-1; i++) 
    {
        ch = password.charAt(i);
        nextCh = password.charAt(i + 1);
        if ((int) ch == ((int) nextCh)) 
        {
            counterOfSameChar++;
        } else 
        {
            maxNumberofRepeatedChars = Math.max(counterOfSameChar, maxNumberofRepeatedChars);
            counterOfSameChar = 0;
            foundMoreThanOneChar = true;
        }
    }

    if (foundMoreThanOneChar)
        return maxNumberofRepeatedChars;
    else
        return counterOfSameChar;
}

您的代码很好,但是重复字符数的答案是counterOfSameChar+1 ,而不是counterOfSameChar 这是因为它查找连续的相同字符,因此“ cc”计数为1,“ ccc”计数为2,依此类推。

当下一个字符与第一个字符相同时,增加counterOfSameChar。 第一次发生这种情况,尽管已经是第二次发生了,但您将其设置为1。 您应该使用1启动counterOfSameChar。

可能的最短代码?

private int countRepeatedChars(String password) {
    int countMax = 0;
    int count = 1;
    int pos = 1;

    if(password != null && password.length() > 1)
    {
        for(pos = 1;pos < password.length();pos++)
        {
            if(password.charAt(pos) == password.charAt(pos - 1))
            {
                count++;
            }
            else
            {
                count = 1;
            }

            if(count > countMax)
            {
                countMax = count;
            }
        }
    }
    else if(password != null)
    {
        countMax = 1;
    }

    return countMax;
}

您数数对os字符即可得出正确答案...

要计算重复字符,您必须计算单个字符,例如:

ch = password.charAt(i);
prevCh = password.charAt(i - 1);
nextCh = password.charAt(i + 1);
if (ch == nextCh || ch == prevCh) {

另请检查您是否在String的范围内(第一个和最后一个字符)。

    Pattern pattern = Pattern.compile("(?<=(.))(?!\\1)");
    String[] count = pattern.split(test,0);
    for(String str : count){
        runningString.append("("+str.length()+")"+str.charAt(0));
    }       
    System.out.println(runningString.toString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM