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.
class Solution {
int maxUniqueSubstrings = 0;
public int maxUniqueSplit(String s) {
Set<String> seen = new HashSet<>();
solve(s, 0, s.length(), 0, seen);
return maxUniqueSubstrings;
}
private void solve(String s, int idx, int n, int ct, Set<String> seen) {
if (idx == n) {
maxUniqueSubstrings = Math.max(maxUniqueSubstrings, ct);
return;
}
if (maxUniqueSubstrings > ct + n - idx)
return;
for (int i = idx + 1; i <= n; i++) {
String sub = s.substring(idx, i);
if (!seen.contains(sub)) {
seen.add(sub);
solve(s, i, n, ct + 1, seen);
seen.remove(sub);
}
}
}
}class Solution {
public int maxUniqueSplit(String s) {
Set<String> seen = new HashSet<>();
return solve(s, 0, s.length(), seen);
}
private int solve(String s, int idx, int n, Set<String> seen) {
if (idx == n)
return 0;
int maxUniqueSubs = 0;
for (int i = idx + 1; i <= n; i++) {
String sub = s.substring(idx, i);
if (!seen.contains(sub)) {
seen.add(sub);
maxUniqueSubs = Math.max(1 + solve(s, i, n, seen), maxUniqueSubs);
seen.remove(sub);
}
}
return maxUniqueSubs;
}
}
class Solution {
int maxAns = 0;
public int maxUniqueSplit(String s) {
Set<String> seen = new HashSet<>();
return solve(s, 0, s.length(), 0, seen);
}
private int solve(String s, int idx, int n, int ct, Set<String> seen) {
if (idx == n)
return ct;
if (maxAns > ct + n - idx)
return 0;
int maxUniqueSubs = 0;
for (int i = idx + 1; i <= n; i++) {
String sub = s.substring(idx, i);
if (!seen.contains(sub)) {
seen.add(sub);
maxUniqueSubs = Math.max(solve(s, i, n, ct + 1, seen), maxUniqueSubs);
seen.remove(sub);
}
}
return maxUniqueSubs;
}
}