描述

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

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐