如何获取给定字符串 abhwasababababuqabab 中最大连续子字符串 ab 的计数

问题描述 投票:0回答:1

如何获取给定字符串 abhwasababababuqabab 中最大连续子串 ab 的计数

输入:abhwasababababuqabab

输出:4 怎么办?

从第 6 个索引到第 13 个索引,我们在中间有 4 个连续的 ab。开始时我们只有 1 个 ab,最后我们有 2 个连续的 ab,但中间有 4 个 ab,所以我们需要返回字符串中连续 ab 的最大计数。

public class MaxConsecutiveAbCount {
    public static int maxConsecutiveAbCount(String s) {
        int maxCount = 0;  // To store the maximum consecutive count
        int currentCount = 0;  // To store the current consecutive count

        for (int i = 0; i < s.length() - 1; i++) {
            // Check if the current and next characters form the substring "ab"
            if (s.substring(i, i + 2).equals("ab")) {
                currentCount++;
            } else {
                // Update maxCount if the current count is greater
                maxCount = Math.max(maxCount, currentCount);
                currentCount = 0;  // Reset current count for a non-"ab" substring
            }
        }

        // Update maxCount again in case the last substring is "ab"
        maxCount = Math.max(maxCount, currentCount);

        return maxCount;
    }

    public static void main(String[] args) {
        String inputString = "abhwasababababuqabab";
        int output = maxConsecutiveAbCount(inputString);
        System.out.println("Output: " + output);
    }
}
java string substring longest-substring
1个回答
0
投票

您的代码不起作用,因为每次它找到

ab
的实例时,它都会检查接下来的 2 个字符,即
b
后跟另一个字符。这将导致它重置计数。

找到

i
后,通过用
i++
递增
ab
来跳过对
b
的检查,可以轻松解决此问题。

public class a {
    public static int maxConsecutiveAbCount(String s) {
        int maxCount = 0;  // To store the maximum consecutive count
        int currentCount = 0;  // To store the current consecutive count

        for (int i = 0; i < s.length() - 1; i++) {
            // Check if the current and next characters form the substring "ab"
            if (s.substring(i, i + 2).equals("ab")) {
                currentCount++;
                i++; // <--- ADD THIS LINE
            } else {
                // Update maxCount if the current count is greater
                maxCount = Math.max(maxCount, currentCount);
                currentCount = 0;  // Reset current count for a non-"ab" substring
            }
        }

        // Update maxCount again in case the last substring is "ab"
        maxCount = Math.max(maxCount, currentCount);

        return maxCount;
    }

    public static void main(String[] args) {
        String inputString = "abhwasababababuqabab";
        int output = maxConsecutiveAbCount(inputString);
        System.out.println("Output: " + output);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.