LeetCode Brush Questions 1417. Reformatting the string

LeetCode Brush Questions 1417. Reformatting the string

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Give you a string of mixed numbers and letters s, where the letters are all lowercase English letters.
    Please reformat the string so that any two adjacent characters are of different types. In other words, letters should be followed by numbers, and numbers should be followed by letters.
    Please return after reformatting the string; if not required to reformat, then returns a null string .
  • Example :
示例 1 :
输入:s = "a0b1c2"
输出:"0a1b2c"
解释:"0a1b2c" 中任意两个相邻字符的类型都不同。 "a0b1c2", "0a1b2c", "0c2a1b" 也是满足题目要求的答案。
示例 2 :
输入:s = "leetcode"
输出:""
解释:"leetcode" 中只有字母,所以无法满足重新格式化的条件。
示例 3 :
输入:s = "1229857369"
输出:""
解释:"1229857369" 中只有数字,所以无法满足重新格式化的条件。
示例 4 :
输入:s = "covid2019"
输出:"c2o0v1i9d"
示例 5 :
输入:s = "ab123"
输出:"1a2b3"
  • Tips :
    • 1 <= s.length <= 500
    • s Only composed of lowercase English letters and/or numbers.
  • Code:
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%的用户
  • Algorithm Description:
    to sthe characters classified by numbers and letters, to the original order is different, using list.insert(index,object)the function, the elements were added to the corresponding list numsand letter; the difference between the length of the list is determined, if more than 2, can not cross Output, return an empty string; if they are equal, it means that △○△○this format is used, and the elements are output interleaved and returned; if the length of one list is greater than the length of another list, it means △○△○△this format, the more one will be sorted first, and the result will be returned .

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106695962