[LeetCode] Find the Longest Semi-Repetitive Substring

2730. Find the Longest Semi-Repetitive Substring

You are given a 0-indexed string s that consists of digits from 0 to 9.

A string t is called a semi-repetitive if there is at most one consecutive pair of the same digits inside t.

Return the length of the longest semi-repetitive substring inside s.

A substring is a contiguous non-empty sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int longestSemiRepetitiveSubstring(string s) {
int res = 0, l = 0, r = 0, n = s.length(), now = 0;
while(r < n) {
while(r < n and now <= 1) {
if(now <= 1) res = max(res, r - l + 1);
if(r + 1 < n and s[r] == s[r+1]) now += 1;
r += 1;
}
if(now <= 1) res = max(res, r - l);
while(r < n and now > 1) {
if(l + 1 < n and s[l] == s[l+1]) now -= 1;
l += 1;
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/11/PS/LeetCode/find-the-longest-semi-repetitive-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.