[LeetCode] Find Longest Special Substring That Occurs Thrice I

10032. Find Longest Special Substring That Occurs Thrice I

You are given a string s that consists of lowercase English letters.

A string is called special if it is made up of only a single character. For example, the string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.

Return the length of the longest special substring of s which occurs at least thrice, or -1 if no special substring occurs at least thrice.

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
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int maximumLength(string s) {
unordered_map<int, unordered_map<int, int>> mp;
int l = 0, r = 0, n = s.length();
while(r < n) {
while(r < n and s[l] == s[r]) r++;
mp[s[l]-'a'][r-l] += 1;
l = r;
}
int res = -1;
for(auto& [_, mmp] : mp) {
for(auto& [k,v] : mmp) {
if(k >= 3) {
res = max(res, k - 2);
}
if(v >= 3) {
res = max(res, k);
}
if(v >= 2) {
res = max(res, k - 1);
}
if(v == 1) {
if(mmp.count(k - 1)) res = max(res, k - 1);
}
}
}
if(res == 0) return -1;
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maximumLength(string s) {
unordered_map<int, unordered_map<int, int>> mp;
int l = 0, r = 0, n = s.length();
int res = -1;
while(r < n) {
while(r < n and s[l] == s[r]) r++;
int len = r - l;
for(int i = 1; i <= 3 and len > 0; i++, len--) {
mp[s[l]-'a'][len] += i;
if(mp[s[l]-'a'][len] >= 3) res = max(res, len);
}
l = r;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/31/PS/LeetCode/find-longest-special-substring-that-occurs-thrice-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.