如何在给定字符串中找到最大数量的 As Substring

How to find max number of As Substring in a given string

JAVA

请帮我写代码。它显示 n-1 作为给定字符串的子字符串中 As 数量的输出。例如,考虑一个字符串“AAABBBBBAAAAAA”,在这个字符串中,As 的最大子串数是 6,但我的代码显示 6-1=5.

{
    public static void main (String[] args) 
    {
        Scanner s=new Scanner(System.in);
        String str=s.nextLine();
        int size=str.length();
        int count=0,max=0;
        
        for(int i=0;i<=size-1;i++)
        {
            if(str.charAt(i)=='A')
            {
                count++;
                max=count;
            }
            else
            {
                count--;
            }
        }
        System.out.print(max);                 
    }
}```

    


 

我认为您正在寻找的解决方案是这个

String str="AAABBBBBAAAAAA";
int size=str.length();
int count=0,max=0;

for(int i=0;i<=size-1;i++)
{
    if(str.charAt(i)=='A')
    {
        count++;
        if(count > max) max = count;
    }
    else
    {
        count=0;
    }
}
System.out.print(max);

这段代码所做的是,每当它发现 A 不存在时,它就会重置计数。此外,最大值仅在 A 的计数大于前一个子字符串时更新。这样就得到了子串的最大长度。

我使用了硬编码的字符串,但您可以按照自己的方式修改它。