From 916067a73a4411b40fc8b63477a30ad29b57dd07 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 21 Oct 2024 23:37:26 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1593.=20Split=20a=20String?= =?UTF-8?q?=20Into=20the=20Max=20Number=20of=20Unique=20Substrings=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/ Signed-off-by: Matej Focko --- ...o-the-max-number-of-unique-substrings.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 java/split-a-string-into-the-max-number-of-unique-substrings.java 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; + } +}