【问题标题】:How to find max number of As Substring in a given string如何在给定字符串中查找最大 As Substring 数
【发布时间】:2021-06-23 13:22:46
【问题描述】:

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 substring


    【解决方案1】:

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

    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 的计数大于前一个子字符串时更新。这样就可以得到子串的最大长度了。

    我使用了一个硬编码的字符串,但是你可以随意修改它。

    【讨论】:

    • 我尝试使用 i
    • 是的,很抱歉这不是问题,我已经更新了我的答案,希望对您有所帮助。 @ShubhamsinghThakur
    • 谢谢@Mr.Furqan Saeed,之前 8 个案例中只有 6 个通过,现在所有 8 个测试案例都通过了。感谢您的帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2016-03-26
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多