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 .
s Only composed of lowercase English letters and/or numbers.
Code:
classSolution:defreformat(self, s:str)->str:
letter, nums, result =[],[],''for i inrange(len(s)):if'0'<= s[i]<='9': nums.insert(0, s[i])if'a'<= s[i]<='z': letter.insert(0, s[i])ifabs(len(letter)-len(nums))>=2:return""iflen(letter)==len(nums):for i inrange(len(nums)):
result = result + letter[i]+ nums[i]iflen(letter)>len(nums):for i inrange(len(nums)):
result = result + letter[i]+ nums[i]
result += letter[-1]iflen(letter)<len(nums):for i inrange(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 .