| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SplitStringIntoTheMaxNumberOfUniqueSubstrings; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SplitStringIntoTheMaxNumberOfUniqueSubstringsBacktracking : ISplitStringIntoTheMaxNumberOfUniqueSubstrings |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * 2^n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MaxUniqueSplit(string s) |
| 3 | 24 | | { |
| 3 | 25 | | return MaxUniqueSplit(s, [], 0); |
| 3 | 26 | | } |
| | 27 | |
|
| | 28 | | private static int MaxUniqueSplit(string s, HashSet<string> hashSet, int start) |
| 95 | 29 | | { |
| 95 | 30 | | if (start == s.Length) |
| 43 | 31 | | { |
| 43 | 32 | | return 0; |
| | 33 | | } |
| | 34 | |
|
| 52 | 35 | | var maxCount = 0; |
| | 36 | |
|
| 322 | 37 | | for (var end = start + 1; end <= s.Length; end++) |
| 109 | 38 | | { |
| 109 | 39 | | var subString = s.Substring(start, end - start); |
| | 40 | |
|
| 109 | 41 | | if (!hashSet.Add(subString)) |
| 17 | 42 | | { |
| 17 | 43 | | continue; |
| | 44 | | } |
| | 45 | |
|
| 92 | 46 | | var count = 1 + MaxUniqueSplit(s, hashSet, end); |
| | 47 | |
|
| 92 | 48 | | maxCount = Math.Max(maxCount, count); |
| | 49 | |
|
| 92 | 50 | | hashSet.Remove(subString); |
| 92 | 51 | | } |
| | 52 | |
|
| 52 | 53 | | return maxCount; |
| 95 | 54 | | } |
| | 55 | | } |