zoukankan      html  css  js  c++  java
  • Leetcode 767. Reorganize String

    Description: Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

    If possible, output any possible result.  If not possible, return the empty string.

    Link: 767. Reorganize String

    Examples:

    Example 1:
    Input: S = "aab"
    Output: "aba"
    
    Example 2:
    Input: S = "aaab"
    Output: ""
    
    Note: S will consist of lowercase letters and have length in range [1, 500].

    思路: 将S按照频率由大到小重新排列,将频率最高的字母取出待处理,检查剩余字母是否足够间隔开最高频率的子串,假设最高频字母为k,出现v次,那么剩余字母个数大于等于v-1个就够了,否则返回 '', 将未使用过的子串S = S[v+v-1:]重复以上步骤,直到S为空。

    class Solution(object):
        def reorganizeString(self, S):
            """
            :type S: str
            :rtype: str
            """
            res = ''
            while len(S) > 0:
                counter = collections.Counter(S)
                s = ''
                for k, v in counter.most_common():
                    s += k*v
                k, v = counter.most_common(1)[0]
                if len(s) - v < v-1:
                    return ''
                i = 0
                sr = list(s[v:])
                for i in range(v-1):
                    res += k + sr[0]
                    sr.pop(0)
                res += k
                S = sr
            return res

    日期: 2021-04-05 刷题真快乐

  • 相关阅读:
    docker network
    mongodb索引
    docker中管理数据
    mysql表备份及还原
    Find and run the whalesay image
    Learn about images & containers
    docker installation on ubuntu
    【转载】熟练利用google hacking来辅助我们快速渗透
    xmind常用快捷键
    漏洞挖掘基础
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14617788.html
Copyright © 2011-2022 走看看