2024-10-21 Daily Challenge
Today I have done leetcode's October LeetCoding Challenge with cpp
.
October LeetCoding Challenge 21
Description
Split a String Into the Max Number of Unique Substrings
Given a string s
, return the maximum number of unique substrings that the given string can be split into.
You can split string s
into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc" Output: 5 Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba" Output: 2 Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa" Output: 1 Explanation: It is impossible to split the string any further.
Constraints:
-
1 <= s.length <= 16
-
s
contains only lower case English letters.
Solution
class Solution {
int maxCount = 0;
int len;
unordered_set<string_view> sequences;
void solve(int pos, int count, string &s) {
if(len - pos < maxCount - count) return;
if(pos >= len) {
maxCount = max(maxCount, count);
return;
}
for(int i = 0; i + pos < len; ++i) {
string_view t(s.data() + pos, i + 1);
if(sequences.count(t)) continue;
sequences.insert(t);
solve(pos + i + 1, count + 1, s);
sequences.erase(t);
}
}
public:
int maxUniqueSplit(string s) {
len = s.length();
solve(0, 0, s);
return maxCount;
}
};