Skip to content

2730. Find the Longest Semi-Repetitive Substring

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int longestSemiRepetitiveSubstring(string s) {
    int ans = 1;
    int prevStart = 0;
    int start = 0;

    for (int i = 1; i < s.length(); ++i) {
      if (s[i] == s[i - 1]) {
        if (prevStart > 0)
          start = prevStart;
        prevStart = i;
      }
      ans = max(ans, i - start + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int longestSemiRepetitiveSubstring(String s) {
    int ans = 1;
    int prevStart = 0;
    int start = 0;

    for (int i = 1; i < s.length(); ++i) {
      if (s.charAt(i) == s.charAt(i - 1)) {
        if (prevStart > 0)
          start = prevStart;
        prevStart = i;
      }
      ans = Math.max(ans, i - start + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestSemiRepetitiveSubstring(self, s: str) -> int:
    ans = 1
    prevStart = 0
    start = 0

    for i in range(1, len(s)):
      if s[i] == s[i - 1]:
        if prevStart > 0:
          start = prevStart
        prevStart = i
      ans = max(ans, i - start + 1)

    return ans