• 最长字串 限制重复长度


    A/B/C代表输入的字母a/b/c的个数,均为非负整数
    不能连续出现三个相同的字母
    求给出可以组成的字长字符串的一个示例

    def solution(A, B, C):
        d = {}
        ret = ''
        d['a'], d['b'], d['c'] = A, B, C
        count0 = 0
        while True:
            for k in d:
                if d[k] > 0:
                    d[k] -= 1
                    ret += k
                else:
                    count0 += 1
            if count0 >= 2:
                break
    
        remain = None
        for k in d:
            if d[k] > 0:
                remain = k
                break
    
        if remain is None:
            return ret
        # abc ---> abac
        replaceTarget = 'abc'.replace(remain, '')
        targetNum = ret.count(replaceTarget)
        replaceCount = min(targetNum, d[remain])
        ret = ret.replace(replaceTarget, replaceTarget[0] + remain + replaceTarget[1], replaceCount)
        d[remain] -= replaceCount
        if d[remain] < 1:
            return ret
    
        # abac ---> aabaac
    
        replaceTarget = remain
        # [1, 1, 12] 14 ccaccbcc 8
        targetNum = ret.replace(remain + remain, '').count(replaceTarget)
        replaceCount = min(targetNum, d[remain])
        ret = ret.replace(replaceTarget, replaceTarget + remain, replaceCount)
        d[remain] -= replaceCount
    
        # 0....n-1
        remainCount = d[remain]
        if ret[0] != remain:
            if remainCount == 1:
                ret = remain + ret
            elif remainCount >= 2:
                ret = remain + remain + ret
                remainCount -= 2
        if ret[-1] != remain:
            if remainCount == 1:
                ret += remain
            elif remainCount >= 2:
                ret += remain + remain
        return ret
    
    
    l = [[0, 1, 2], [2, 2, 2], [2, 3, 4], [2, 3, 5], [1, 3, 7], [12, 3, 0], [1, 3, 1], [1, 5, 1], [0, 0, 12], [1, 1, 12]]
    for i in l:
        A, B, C = i
        s = solution(A, B, C)
        print(i, sum(i), s, len(s))
    
    '''
    [0, 1, 2] 3 bcc 3
    [2, 2, 2] 6 abcabc 6
    [2, 3, 4] 9 abcabcbcc 9
    [2, 3, 5] 10 acbcabcbcc 10
    [1, 3, 7] 11 accbccbccbc 11
    [12, 3, 0] 15 aabaabaa 8
    [1, 3, 1] 5 abbcb 5
    [1, 5, 1] 7 babbcbb 7
    [0, 0, 12] 12 cc 2
    [1, 1, 12] 14 ccaccbcc 8
    '''
    

      

      

  • 相关阅读:
    73. Set Matrix Zeroes
    289. Game of Live
    212. Word Search II
    79. Word Search
    142. Linked List Cycle II
    141. Linked List Cycle
    287. Find the Duplicate Number
    260. Single Number III
    137. Single Number II
    Oracle EBS中有关Form的触发器的执行顺序
  • 原文地址:https://www.cnblogs.com/rsapaper/p/11152182.html
Copyright © 2020-2023  润新知