【leetcode】1156. Swap For Longest Repeated Character Substring

题目如下:

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.

解题思路:我的方法是合并相同的连续字符,并记录其连续的个数,例如text="aaabbaaa",解析成char=['a','b','a'],amount=[3,2,3],amount[i]表示char[i]在text中连续出现的次数。要使得只交换一次可以获得的最大值,有这么几种情况:

1. amount[i]是最大值,同时text中除了这一段没有其他地方出现该字符,那么最大值就是amount[i];

2.amount[i]是最大值,同时text中除了这一段没有其他地方出现该字符,但是两者相距超过一个字符的长度,这表明可以交换一个字符到amount[i]对应的这段,最大值是amount[i]+1;

3.amount[i-1]和amount[i+1]对应的字符相同,同时amount[i] = 1,这时最大值是amount[i-1] + amount[i+1] - 1。

代码如下:

class Solution(object):
    def maxRepOpt1(self, text):
        """
        :type text: str
        :rtype: int
        """
        dic = {}
        char = []
        amount = []
        last = None
        count = 1
        text += '#'
        for i in text:
            dic[i] = dic.setdefault(i,0) + 1
            if last == None:
                last = i
            elif i == last:
                count += 1
            else:
                char.append(last)
                amount.append(count)
                count = 1
                last = i
        res = 0
        for i in range(len(char)):
            if i > 0 and i < len(char) - 1 and char[i-1] == char[i+1] and amount[i] == 1:
                v = amount[i-1] + amount[i+1]
                if dic[char[i-1]] > v:
                    v += 1
                res = max(res,v)
            if dic[char[i]] > amount[i]:res = max(res,amount[i] + 1)
            else:res = max(res,amount[i])
        return res

 

转载于:https://www.cnblogs.com/seyjs/p/11376720.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值