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
  • 相关阅读:
    转:【WebDriver】封装GET方法来解决页面跳转不稳定的问题
    转:Selenium2.0 click()不生效的解决办法
    (转).net下Selenium2使用方法总结
    转:从测试员到测试负责人
    7.2.4 MediaRecorder输出和录制
    7.2.3 MediaRecorder音频编码器
    7.2.2 MediaRecorder输出格式
    7.2.1 MediaRecorder 音频源
    7.2 定制音频捕获
    7.1 通过意图捕获音频
  • 原文地址:https://www.cnblogs.com/seyjs/p/11376720.html
Copyright © 2011-2022 走看看