Backtracking to maximize the split of a string
Here is the problem (medium difficulty, LC): https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc" Output: 5 Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba" Output: 2 Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa" Output: 1 Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16scontains only lower case English letters.
Given the small boundaries we'll try a simple exponential approach with standard backtracking: keep splitting the string if you can (use a hashtable to keep track) and the moment that you've found a potential good split, check for the max one. Code is down below, cheers, ACC.
public class Solution {
public int MaxUniqueSplit(string s)
{
int retVal = 0;
MaxUniqueSplit(s, new Hashtable(), 0, ref retVal);
return retVal;
}
private void MaxUniqueSplit(string s, Hashtable seen, int currentCount, ref int retVal)
{
if (String.IsNullOrEmpty(s))
{
retVal = Math.Max(retVal, currentCount);
return;
}
string part = "";
for (int i = 0; i < s.Length; i++)
{
part += s[i].ToString();
if (!seen.ContainsKey(part))
{
seen.Add(part, true);
MaxUniqueSplit(s.Substring(i + 1), seen, currentCount + 1, ref retVal);
seen.Remove(part);
}
}
}
}
Comments
Post a Comment