Reformat The String Problem
Description
LeetCode Problem 1417.
You are given an 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.
Example 1:
Input: s = "a0b1c2"
Output: "0a1b2c"
Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
Input: s = "leetcode"
Output: ""
Explanation: "leetcode" has only characters so we cannot separate them by digits.
Example 3:
Input: s = "1229857369"
Output: ""
Explanation: "1229857369" has only digits so we cannot separate them by characters.
Constraints:
1 <= s.length <= 500sconsists of only lowercase English letters and/or digits.
Solution
Approach: Split and Interleave
Put the letters in one list and the digits in another. In the result, the two kinds must alternate, so their counts can differ by at most one:
- If they differ by more than one, there is no answer: return
""(e.g."leetcode"has no digits at all). - Otherwise, let
abe the larger group (either one if they are equal). The result has to start witha: writea[0] b[0] a[1] b[1] ..., and ifahas one extra character, add it at the end.
Starting with the smaller group would fail when the counts differ, as in "ab1": 1ab puts two letters together, while a1b works. Any arrangement that alternates is accepted, so we do not have to match the example's output.
Complexity: O(n) time and O(n) space.
class Solution:
def reformat(self, s: str) -> str:
a = [c for c in s if c.isalpha()]
b = [c for c in s if c.isdigit()]
if abs(len(a) - len(b)) > 1:
return ""
if len(a) < len(b):
a, b = b, a # the larger group has to go first (and last)
ans = []
for x, y in zip(a, b):
ans.append(x + y)
if len(a) > len(b):
ans.append(a[-1])
return "".join(ans)