LeetCode刷题之1417. 重新格式化字符串

LeetCode刷题之1417. 重新格式化字符串

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
  • 题目
    给你一个混合了数字和字母的字符串 s,其中的字母均为小写英文字母。
    请你将该字符串重新格式化,使得任意两个相邻字符的类型都不同。也就是说,字母后面应该跟着数字,而数字后面应该跟着字母。
    请你返回 重新格式化后 的字符串;如果无法按要求重新格式化,则返回一个 空字符串
  • 示例
示例 1 :
输入:s = "a0b1c2"
输出:"0a1b2c"
解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。
示例 2 :
输入:s = "leetcode"
输出:""
解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。
示例 3 :
输入:s = "1229857369"
输出:""
解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。
示例 4 :
输入:s = "covid2019"
输出:"c2o0v1i9d"
示例 5 :
输入:s = "ab123"
输出:"1a2b3"
  • 提示
    • 1 <= s.length <= 500
    • s 仅由小写英文字母和/或数字组成。
  • 代码:
class Solution:
    def reformat(self, s: str) -> str:
        letter, nums, result = [], [], ''
        for i in range(len(s)):
            if '0' <= s[i] <= '9': nums.insert(0, s[i])
            if 'a' <= s[i] <= 'z': letter.insert(0, s[i])
        if abs(len(letter) - len(nums)) >= 2: return ""
        if len(letter) == len(nums):
            for i in range(len(nums)):
                result = result + letter[i] + nums[i]
        if len(letter) > len(nums):
            for i in range(len(nums)):
                result = result + letter[i] + nums[i]
            result += letter[-1]
        if len(letter) < len(nums):
            for i in range(len(letter)):
                result = result + nums[i] + letter[i]
            result += nums[-1]  
        return result      
# 执行用时 :64 ms, 在所有 Python3 提交中击败了32.01%的用户
# 内存消耗 :13.8 MB, 在所有 Python3 提交中击败了100.00%的用户
  • 算法说明:
    s中的中字符按照数字和字母进行分类,为了和原始的次序有所不同,采用list.insert(index,object)函数,将元素分别添加到对应的列表numsletter;判断列表长度之差,如果大于2,则无法交叉输出,返回空字符串;如果相等,说明是△○△○这种格式,将元素交叉输出返回;如果一个列表的长度大于另一个列表长度,说明是△○△○△这种格式,将较多的一种先排列,返回结果。

猜你喜欢

转载自blog.csdn.net/qq_34331113/article/details/106695962
今日推荐