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.
方法:backtracking(可惜一开始没有想到用这个方法)
思路:用一个set来记录所有出现过的substring,backtrack来处理所有可能得到的结果。然后取最大值。(感觉也有点像是brute force)
time complexity:O(2^N)
class Solution: def maxUniqueSplit(self, s: str) -> int: if not s or len(s) == 0: return 0 self.res = 0 self.dfs(s, 0, 0, set()) return self.res def dfs(self, s, p, length, visited): if length == len(s): self.res = max(self.res, len(visited)) return for i in range(p, len(s)): if s[p:i+1] not in visited: visited.add(s[p:i+1]) self.dfs(s, i+1, length+i+1-p, visited) visited.remove(s[p:i+1])