题目描述
如果字符串中的所有字符都相同,那么这个字符串是单字符重复的字符串。
给你一个字符串 text,你只能交换其中两个字符一次或者什么都不做,然后得到一些单字符重复的子串。返回其中最长的子串的长度。
示例 1:
输入:text = "ababa"
输出:3
示例 2:
输入:text = "aaabaaa"
输出:6
示例 3:
输入:text = "aaabbaaa"
输出:4
示例 4:
输入:text = "aaaaa"
输出:5
示例 5:
输入:text = "abcdef"
输出:1
提示:
1 <= text.length <= 20000
text 仅由小写英文字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-for-maximum-repeated-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
class Solution {
public:
int maxRepOpt1(string text) {
int ans = 0,len = text.length();
unordered_map<char,vector<pair<int,int>>> mp;
int i=0;
while(i<len){
int s = i;
while(i<len && text[i] == text[s]) ++i;
mp[text[s]].push_back(make_pair(s,i-1));
}
for(auto it : mp){
auto vect = it.second;
int tl = vect.size();
for(i=0;i<tl;++i){
bool change = false;
int tmp = vect[i].second - vect[i].first+1;
if(i+1<tl && vect[i].second+2==vect[i+1].first){
change = true;
tmp = max(tmp,vect[i+1].second-vect[i].first);
if(tl>2) tmp+=1;
}
if(!change && (i>0||i+1<tl)) tmp+=1;
ans = max(ans,tmp);
}
}
return ans;
}
};