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 ofswhich occurs at least thrice, or-1if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
classSolution { public: intmaximumLength(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
classSolution { public: intmaximumLength(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 <= 3and 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; } };