Given an alphanumeric string s
, return the string after reformating it so that no two adjacent characters are of the same type. Assume that to reformat the string, you may only use the string’s existing characters. If it’s impossible to reformat the string, return an empty string.
Example:
s = "a0b1c2"
"0a1b2c"
def reformat(s: str) -> str:
letters = []
digits = []
# Separate characters
for char in s:
if char.isdigit():
digits.append(char)
else:
letters.append(char)
# Check for the possibility of reformat
if abs(len(letters) - len(digits)) > 1:
return ""
# Decide the order of alternating based on count
if len(letters) > len(digits):
longer, shorter = letters, digits
else:
longer, shorter = digits, letters
result = []
# Merge the characters
for i in range(len(shorter)):
result.append(longer[i])
result.append(shorter[i])
if len(longer) > len(shorter):
result.append(longer[-1])
return "".join(result)
# Example usage
print(reformat("a0b1c2")) # Output: "0a1b2c" or "a0b1c2" etc.
s
.Overall, the solution runs in linear time, O(n), because both the operations of separating and merging are linear in nature. The space complexity is also O(n) due to the storage of characters in separate lists.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?