-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode_1593.java
29 lines (25 loc) · 1.06 KB
/
Leetcode_1593.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int maxUniqueSplit(String s) {
Set<String> seen = new HashSet<>();
return backtrack(s, 0, seen);
}
private int backtrack(String s, int start, Set<String> seen) {
// Base case: If we reach the end of the string, return 0 (no more substrings to add)
if (start == s.length()) return 0;
int maxCount = 0;
// Try every possible substring starting from 'start'
for (int end = start + 1; end <= s.length(); ++end) {
String substring = s.substring(start, end);
// If the substring is unique
if (!seen.contains(substring)) {
// Add the substring to the seen set
seen.add(substring);
// Recursively count unique substrings from the next position
maxCount = Math.max(maxCount, 1 + backtrack(s, end, seen));
// Backtrack: remove the substring from the seen set
seen.remove(substring);
}
}
return maxCount;
}
}