diff --git a/java/split-a-string-into-the-max-number-of-unique-substrings.java b/java/split-a-string-into-the-max-number-of-unique-substrings.java new file mode 100644 index 0000000..c64e55a --- /dev/null +++ b/java/split-a-string-into-the-max-number-of-unique-substrings.java @@ -0,0 +1,36 @@ +class Solution { + private Set 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; + } +}