LeetCode 2730: Find the Longest Semi-Repetitive Substring Solution

Master LeetCode problem 2730 (Find the Longest Semi-Repetitive Substring), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2730. Find the Longest Semi-Repetitive Substring

Problem Explanation

Explanation

To find the longest semi-repetitive substring in a given digit string, we can use a sliding window approach. We will maintain two pointers, start and end, to represent the current window. As we iterate through the string, we will keep track of the count of the current digit and the previous digit. If the count of the current digit exceeds 1 and the previous digit is the same as the current digit, we will update the start pointer to move the window to the right until the condition is satisfied. We will also update the longest length of the semi-repetitive substring found so far.

Time complexity: O(n) Space complexity: O(1)

Solution Code

class Solution {
    public int longestSemiRepetitiveSubstring(String s) {
        int n = s.length();
        int start = 0, end = 0;
        int prevCount = 0, currCount = 0;
        int longest = 0;

        while (end < n) {
            char curr = s.charAt(end);
            if (end > 0 && s.charAt(end - 1) == curr) {
                currCount++;
            } else {
                currCount = 1;
            }
            if (currCount > 1 && s.charAt(end - 1) == curr) {
                while (currCount > 1) {
                    char prev = s.charAt(start);
                    if (s.charAt(start + 1) == prev) {
                        prevCount--;
                    }
                    start++;
                    currCount--;
                }
            }
            longest = Math.max(longest, end - start + 1);
            end++;
        }

        return longest;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2730 (Find the Longest Semi-Repetitive Substring)?

This page provides optimized solutions for LeetCode problem 2730 (Find the Longest Semi-Repetitive Substring) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2730 (Find the Longest Semi-Repetitive Substring)?

The time complexity for LeetCode 2730 (Find the Longest Semi-Repetitive Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2730 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2730 in Java, C++, or Python.

Back to LeetCode Solutions