Check if String Is Decomposable Into Value-Equal Substrings Problem
Description
LeetCode Problem 1933.
A value-equal string is a string where all characters are the same.
- For example,
"1111"and"33"are value-equal strings. - In contrast,
"123"is not a value-equal string.
Given a digit string s, decompose the string into some number of consecutive value-equal substrings where exactly one substring has a length of 2 and the remaining substrings have a length of 3.
Return true if you can decompose s according to the above rules. Otherwise, return false.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "000111000"
Output: false
Explanation: s cannot be decomposed according to the rules because ["000", "111", "000"] does not have a substring of length 2.
Example 2:
Input: s = "00011111222"
Output: true
Explanation: s can be decomposed into ["000", "111", "11", "222"].
Example 3:
Input: s = "011100022233"
Output: false
Explanation: s cannot be decomposed according to the rules because of the first '0'.
Constraints:
1 <= s.length <= 1000sconsists of only digits'0'through'9'.
Solution
Approach: Run Lengths
Split s into maximal runs of equal digits. Each run must be cut into pieces of length 3, except for exactly one piece of length 2 in the whole string.
So a run of length L works only if L % 3 is 0 (all pieces are 3) or 2 (all 3s plus the single 2); a remainder of 1 can never be cut and the answer is false. Count the runs with remainder 2: there must be exactly one.
Complexity: O(n) time and O(1) extra space, where n is the length of s.
class Solution:
def isDecomposable(self, s: str) -> bool:
i, n = 0, len(s)
cnt2 = 0
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
if (j - i) % 3 == 1:
return False
cnt2 += (j - i) % 3 == 2
if cnt2 > 1:
return False
i = j
return cnt2 == 1