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 of2 and the remaining substrings have a length of3.
Return trueif you can decomposesaccording to the above rules. Otherwise, returnfalse.
A substring is a contiguous sequence of characters in a string.
Input: s ="000111000"Output: falseExplanation: s cannot be decomposed according to the rules because ["000","111","000"] does not have a substring of length 2.
Example 2:
1
2
3
Input: s ="00011111222"Output: trueExplanation: s can be decomposed into ["000","111","11","222"].
Example 3:
1
2
3
Input: s ="011100022233"Output: falseExplanation: s cannot be decomposed according to the rules because of the first '0'.
We want to split the string into value-equal substrings, with exactly one of length 2 and the rest of length 3. The greedy approach is to always take groups of 3 when possible, and use a group of 2 only once when necessary.
By grouping as many 3-length substrings as possible, we minimize the number of 2-length substrings. If at any point we need more than one 2-length group, or if a group of length 1 remains, the decomposition is not possible. This works because the only allowed group sizes are 2 (once) and 3 (any number of times).
classSolution {
public:bool isDecomposable(string s) {
int n = s.size(), two =0;
for (int i =0; i < n;) {
int j = i;
while (j < n && s[j] == s[i]) ++j;
int len = j - i;
while (len >=3) len -=3;
if (len ==2) ++two;
elseif (len ==1) return false;
i = j;
}
return two ==1;
}
};
classSolution {
publicbooleanisDecomposable(String s) {
int n = s.length(), two = 0;
for (int i = 0; i < n;) {
int j = i;
while (j < n && s.charAt(j) == s.charAt(i)) j++;
int len = j - i;
while (len >= 3) len -= 3;
if (len == 2) two++;
elseif (len == 1) returnfalse;
i = j;
}
return two == 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funisDecomposable(s: String): Boolean {
var i = 0var two = 0while (i < s.length) {
var j = i
while (j < s.length && s[j] == s[i]) j++var len = j - i
while (len >=3) len -=3if (len ==2) two++elseif (len ==1) returnfalse i = j
}
return two ==1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defis_decomposable(self, s: str) -> bool:
n, two = len(s), 0 i =0while i < n:
j = i
while j < n and s[j] == s[i]:
j +=1 l = j - i
while l >=3:
l -=3if l ==2:
two +=1elif l ==1:
returnFalse i = j
return two ==1
impl Solution {
pubfnis_decomposable(s: String) -> bool {
let n = s.len();
let s = s.as_bytes();
letmut i =0;
letmut two =0;
while i < n {
letmut j = i;
while j < n && s[j] == s[i] {
j +=1;
}
letmut l = j - i;
while l >=3 {
l -=3;
}
if l ==2 {
two +=1;
} elseif l ==1 {
returnfalse;
}
i = j;
}
two ==1 }
}