描述

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.

Example 1:

Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.	

Example 2:

Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.

Example 3:

Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.

Example 4:

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

Example 5:

Input: s = "ab123"
Output: "1a2b3"

Note:

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

解析

根据题意,就是如果纯字母或者纯数字的字符串则直接返回空字符串,如果字母和数字不两两相连则返回重新拼接的字符串,否则返回空字符串。关键之处就在于将 s 中的字母和数字都各自提出来,且两者长度差的绝对值小于等于 1 则,然后将字母和数字间隔拼接起来即可。

解答

 class Solution(object):
    def reformat(self, s):
        """
        :type s: str
        :rtype: str
        """
        alpha = "".join(re.findall(r"[a-z]{1}", s))
        digit = "".join(re.findall(r"[0-9]{1}", s))
        if abs(len(alpha) - len(digit)) > 1:
            return ""
        if len(alpha) < len(digit):
            alpha, digit = digit, alpha
        return "".join([i for t in zip(alpha, digit) for i in t] + [alpha[len(digit):]])

运行结果

Runtime: 36 ms, faster than 66.04% of Python online submissions for Reformat The String.
Memory Usage: 13.7 MB, less than 30.82% of Python online submissions for Reformat The String.

原题链接:https://leetcode.com/problems/reformat-the-string/

您的支持是我最大的动力

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐