Skip to content

Latest commit

 

History

History

1593

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 <= 16

  • s contains only lower case English letters.

Related Topics:
Backtracking

Solution 1. Backtrack

// OJ: https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
    unordered_set<string> m;
    int ans = 0;
    void dfs(string &s, int i) {
        if (i == s.size()) {
            ans = max(ans, (int)m.size());
            return;
        }
        for (int j = i; j < s.size(); ++j) {
            string sub = s.substr(i, j - i + 1);
            if (m.count(sub)) continue;
            m.insert(sub);
            dfs(s, j + 1);
            m.erase(sub);
        }
    }
public:
    int maxUniqueSplit(string s) {
        dfs(s, 0);
        return ans;
    }
};