Leetcode 1417. Reformat The String Python3解法
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.
Examples:
Input: s = "a0b1c2"
Output: "0a1b2c"
Input: s = "covid2019"
Output: "c2o0v1i9d"
Input: s = "leetcode"
Output: ""
Input: s = "1229857369"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of only lowercase English letters and/or digits.
思路
本题要求将数字和字母间隔排开,要求相邻的两个字符不可以是同种类型。首先,我们观察一下满足条件的结果有什么特征,例如‘a0b1c2’, ‘3a0b1c2‘, ‘a0b1c’,不难发现,字母和数字的个数最多差一个,否则同类型字符就要相邻。所以我们的思路也就有了
- 计算字符数量
- 如果不同类别字符数量差距 >= 2,则不满足条件,所以返回
""
- 如果满足条件,则判断是字母在前,还是数字在前
解法一:列举所有情况
class Solution:
def reformat(self, s: str) -> str:
char = []
nums = []
# 将字母和数字分别存在两个新的list里
for i in s:
if i.isalpha():
char.append(i)
if i.isnumeric():
nums.append(i)
if abs(len(char) - len(nums)) >= 2:
return ""
# 如果字母和数字数量差2个以内
elif len(char) > len(nums):
ans = []
# 如果字母多于数值,从字母开始
while nums:
ans.append(char.pop())
ans.append(nums.pop())
ans.append(char.pop())
return ''.join(ans)
elif len(char) <= len(nums):
ans = []
# 如果数字多于数值,从数字开始
while char:
ans.append(nums.pop())
ans.append(char.pop())
if nums:
ans.append(nums.pop())
return ''.join(ans)
解法二:巧用zip
class Solution:
def reformat(self, s: str) -> str:
char = []
nums = []
for i in s:
if i.isalpha():
char.append(i)
if i.isnumeric():
nums.append(i)
if abs(len(char) - len(nums)) >= 2:
return ""
elif len(char) >= len(nums):
ans = list(itertools.zip_longest(char, nums, fillvalue=''))
else:
ans = list(itertools.zip_longest(nums, char, fillvalue=''))
return ''.join("%s%s" % tup for tup in ans)