Leetcode_Sort --767. Reorganize String [medium]

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.
给定一个字符串S,检查S中的字母是否能够被重新排序成相邻字母不同的形式
如果可以,返回任意可能的结果;如果不行,返回空字符串

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由小写字母组成且长度在1到500之间

Solution:

Python

class Solution:
    def reorganizeString(self, S):
        """
        :type S: str
        :rtype: str
        """
        a = sorted(sorted(S), key=S.count)
        h = len(a) // 2
        a[1::2], a[::2] = a[:h], a[h:] # 奇数位对应前半部分,偶数位对应后半部分
        return ''.join(a) * (a[-1:] != a[-2:-1])

上述代码是参考Discuss中的一个方法来完成的。其思路是:首先将S字符串进行排序,sorted函数会得到一个list形式,例如 S=‘abdbca’ ,在排序之后会得到 [‘c’, ‘d’, ‘a’, ‘a’, ‘b’, ‘b’],然后将得到的数组从中间分割成两部分,将list a的前一部分存储到a的奇数位置上,后一部分存储到a的偶数位置上,最后检查所得数组的最后两位是否为相同的数,如果是那么返回空字符串(注:string*False = [],string*True = string),如果否则将list a通过join函数变成数组返回
h = len(a)//2,’//’表示整除,当结果为小数时向下去整。当a长度为奇数时,返回的是中间元素左边元素的序号,例如len(a) = 3,那么h = 1,而 a[:h] = a[:1]不包括a[1],a[h:] = a[1:2] 包括a[1]。

eg:
a = [1,2,3,4,5],h = len(a)//2 = 2,a[:2] = [1,2],a[2:] = [3,4,5]
a = [1,2,3,4],h= len(a)//2 = 2,a[:2] = [1,2],a[2:] = [3,4]

n为列表a的长度,当n为奇数时,偶数位的个数比奇数位的个数多一;当n为偶数时,偶数位的个数与奇数个位一样多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值