Leetcode 1417. Reformat The String Python3解法

Leetcode 1417. Reformat The String Python3解法

Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Examples:

Input: s = "a0b1c2"
Output: "0a1b2c"

Input: s = "covid2019"
Output: "c2o0v1i9d"

Input: s = "leetcode"
Output: ""

Input: s = "1229857369"
Output: ""

Constraints:

1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.

思路

本题要求将数字和字母间隔排开,要求相邻的两个字符不可以是同种类型。首先,我们观察一下满足条件的结果有什么特征,例如‘a0b1c2’, ‘3a0b1c2‘, ‘a0b1c’,不难发现,字母和数字的个数最多差一个,否则同类型字符就要相邻。所以我们的思路也就有了

  • 计算字符数量
  • 如果不同类别字符数量差距 >= 2,则不满足条件,所以返回 ""
  • 如果满足条件,则判断是字母在前,还是数字在前

解法一:列举所有情况

class Solution:
    def reformat(self, s: str) -> str:
        char = []
        nums = []
        # 将字母和数字分别存在两个新的list里
        for i in s:
            if i.isalpha():
                char.append(i)
            
            if i.isnumeric():
                nums.append(i)
        if abs(len(char) - len(nums)) >= 2:
            return ""
        # 如果字母和数字数量差2个以内
        elif len(char) > len(nums):
            ans = []
            # 如果字母多于数值,从字母开始
            while nums:
                ans.append(char.pop())
                ans.append(nums.pop())
            ans.append(char.pop())
            return ''.join(ans)
        
        elif len(char) <= len(nums):
            ans = []
            # 如果数字多于数值,从数字开始
            while char:
                ans.append(nums.pop())
                ans.append(char.pop())
            if nums:
                ans.append(nums.pop())
            return ''.join(ans)

解法二:巧用zip

class Solution:
    def reformat(self, s: str) -> str:
        char = []
        nums = []
        
        for i in s:
            if i.isalpha():
                char.append(i)
            
            if i.isnumeric():
                nums.append(i)
        if abs(len(char) - len(nums)) >= 2:
            return ""
        
        elif len(char) >= len(nums):
            ans = list(itertools.zip_longest(char, nums, fillvalue=''))
        else:
            ans = list(itertools.zip_longest(nums, char, fillvalue=''))
        
        return ''.join("%s%s" % tup for tup in ans)
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值