java: add «1593. Split a String Into the Max Number of Unique Substrings»
URL: https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
9fabcc111d
commit
916067a73a
1 changed files with 36 additions and 0 deletions
|
@ -0,0 +1,36 @@
|
|||
class Solution {
|
||||
private Set<String> seen;
|
||||
private int maxCount;
|
||||
|
||||
private void backtrack(String s, int start, int count) {
|
||||
if (count + (s.length() - start) <= maxCount) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (start == s.length()) {
|
||||
maxCount = Math.max(maxCount, count);
|
||||
return;
|
||||
}
|
||||
|
||||
for (int end = start + 1; end <= s.length(); ++end) {
|
||||
var sub = s.substring(start, end);
|
||||
if (seen.contains(sub)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(sub);
|
||||
backtrack(s, end, count + 1);
|
||||
seen.remove(sub);
|
||||
}
|
||||
}
|
||||
|
||||
public int maxUniqueSplit(String s) {
|
||||
seen = new HashSet<>();
|
||||
maxCount = 0;
|
||||
|
||||
backtrack(s, 0, 0);
|
||||
|
||||
seen = null;
|
||||
return maxCount;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue