zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    HTTP协议中常用相应的状态码总结
    mysql 用户管理
    史上最全的mysql聚合函数总结(与分组一起使用)
    jQuery+masonry实现瀑布流
    MySQL Workbench 导入导出乱码解决方法
    在Google Maps 上点击标签显示说明并保持不消失
    在Google Maps 上点击标签后显示说明
    如何在Google Maps 添加多个标记
    如何在 Google 地图中添加标记和说明
    Google Maps API3 之 Hello World
  • 原文地址:https://www.cnblogs.com/seyjs/p/11376720.html
Copyright © 2011-2022 走看看