Leetcode 1156:单字符重复子串的最大长度

题目描述

如果字符串中的所有字符都相同,那么这个字符串是单字符重复的字符串。

给你一个字符串 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值