LeetCode 1593. Split a String Into the Max Number of Unique Substrings (Medium)
阿新 • • 發佈:2020-11-17
Given a strings
,returnthe maximumnumber of unique substrings that the given string can be split into.
You can split strings
into any list ofnon-empty substrings, where the concatenation of the substrings forms the original string.However, you must split the substrings such that all of them areunique.
Asubstringis 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
containsonly 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])