[LeetCode] Splitting a String Into Descending Consecutive Values

1849. Splitting a String Into Descending Consecutive Values

You are given a string s that consists of only digits.

Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.

  • For example, the string s = “0090089” can be split into [“0090”, “089”] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
  • Another example, the string s = “001” can be split into [“0”, “01”], [“00”, “1”], or [“0”, “0”, “1”]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.

Return true if it is possible to split s​​​​​​ as described above, or false otherwise.

A substring is a contiguous sequence of characters in a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
bool isDescendingOrder(string& s, int pos, unsigned long long prev) {
if(pos == s.length()) return true;
unsigned long long val = 0;
for(int i = pos; i < s.length(); i++) {
val = val * 10 + (s[i] & 0b1111);
if(val > prev) return false;
if(val + 1 == prev && isDescendingOrder(s, i + 1, val)) return true;
}
return false;
}
public:
bool splitString(string s) {
unsigned long long val = 0;
for(int i = 0; i < s.length() - 1; i++) {
val = val * 10 + (s[i] & 0b1111);
if(isDescendingOrder(s, i + 1, val)) return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/02/PS/LeetCode/splitting-a-string-into-descending-consecutive-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.