[leetcode] 1156. Swap For Longest Repeated Character Substring

Description

Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.

Example 1:

Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.

Example 2:

Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.

Example 3:

Input: text = "aaabbaaa"
Output: 4

Example 4:

Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.

Example 5:

Input: text = "abcdef"
Output: 1

Constraints:

  • 1 <= text.length <= 20000
  • text consist of lowercase English characters only.

分析

题目的意思是:给定一个字符串,交换其中的两个字母,使得字符串连续重复字符数最长。这道题我看了一下思路,首先用group记录一下每个字符的频率,例如 S = “AAABBCB” group为, [[A,3],[B,2],[C,1],[B,1]],然后d记录每个字符的总数,{A:3,B:3,C:1},
然后最长重复字符有两种情况,第一种情况是group[i][ch]+1,即交换一个字符过来,交换过来的字符不一定与该ch字符相等,所以这时候d字典就是来限制的哈;另一种是两个相等的字符串之间只有一个其他字符串,然后把它交换到其他位置就可以了,当然交换来的字符串不一定是与现在的连续字符一样,所以这时候也是d来做限制哈。所以公式为:

res=max(res,min(cnt+1,d[k]))
res=max(res,min(group[i-1][1]+group[i+1][1]+1,d[k]))

两个循环就能把这两种情况都包括在内了哈,当然我也没做出来,只是分析一下,哈哈哈

代码

class Solution:
    def maxRepOpt1(self, text: str) -> int:
        group = []
        i=0
        n=len(text)
        d={}
        while(i<n):
            ch=text[i]
            cnt=0
            while(i<n and text[i]==ch):
                cnt+=1
                i+=1
            group.append((ch,cnt))
            d[ch]=d.get(ch,0)+cnt
        res=0
        for i in range(len(group)):
            k,cnt=group[i]
            res=max(res,min(cnt+1,d[k]))
        for i in range(1,len(group)-1):
            k=group[i-1][0]
            if(group[i-1][0]==group[i+1][0] and group[i][1]==1):
                res=max(res,min(group[i-1][1]+group[i+1][1]+1,d[k]))
        return res

参考文献

[LeetCode] Python 3, HashTable, O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值