class Solution {
public:
int maximumLength(string s) {
vector<unordered_map<int, int>> freqPerLengthPerChar(26, unordered_map<int, int>{});
int ltIdx = 0;
int rtIdx = 0;
while (ltIdx < s.size())
{
char ltChar = s[ltIdx];
char rtChar = s[rtIdx];
while (ltChar == rtChar)
{
++rtIdx;
if (rtIdx >= s.size())
{
break;
}
rtChar = s[rtIdx];
}
int length = rtIdx - ltIdx;
int charIdx = ltChar - 'a';
if (freqPerLengthPerChar[charIdx].find(length) == freqPerLengthPerChar[charIdx].end())
{
freqPerLengthPerChar[charIdx].insert({length,0});
}
++freqPerLengthPerChar[charIdx][length];
ltIdx += length;
}
int maxLength = -1;
int maxChar = -1;
for (int ii=0; ii<freqPerLengthPerChar.size(); ++ii)
{
if (freqPerLengthPerChar[ii].size() <= 0)
{
continue;
}
vector<int> lengths{};
for (auto p : freqPerLengthPerChar[ii])
{
lengths.push_back(p.first);
}
sort(lengths.begin(), lengths.end(),[](int a, int b){return a > b;});
int topLength = lengths[0];
int topLengthCount = freqPerLengthPerChar[ii][topLength];
if (topLengthCount >= 3)
{
if (topLength > maxLength)
{
maxLength = topLength;
}
}
else if (topLengthCount == 2)
{
int topLengthCountMinus1 = topLength - 1;
if (topLengthCountMinus1 > 0 && topLengthCountMinus1 > maxLength)
{
maxLength = topLengthCountMinus1;
}
}
else
{
int topLengthMinus2 = topLength - 2;
if (topLengthMinus2 > 0 && topLengthMinus2 > maxLength)
{
maxLength = topLengthMinus2;
}
}
if (lengths.size() >= 2)
{
int secondLength = lengths[1];
if (secondLength > maxLength)
{
maxLength = secondLength;
}
}
}
return maxLength;
}
};