Skip to content

Commit

Permalink
dfs | backtracking
Browse files Browse the repository at this point in the history
leetcode 102124
  • Loading branch information
Zhenye-Na committed Oct 21, 2024
1 parent 87c1f0c commit 408e83d
Showing 1 changed file with 87 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#
# @lc app=leetcode id=1593 lang=python3
#
# [1593] Split a String Into the Max Number of Unique Substrings
#
# https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/description/
#
# algorithms
# Medium (57.11%)
# Likes: 978
# Dislikes: 44
# Total Accepted: 52.5K
# Total Submissions: 85.2K
# Testcase Example: '"ababccc"'
#
# 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.
#
#
#
#


# @lc code=start
class Solution:
def maxUniqueSplit(self, s: str) -> int:
self.max_split = 0
self.backtrack(s, 0, set())
return self.max_split

def backtrack(self, s, start, unique_substrings):
if start == len(s):
self.max_split = max(self.max_split, len(unique_substrings))
return

for end in range(start + 1, len(s) + 1):
substring = s[start:end]
if substring not in unique_substrings:
unique_substrings.add(substring)
self.backtrack(s, end, unique_substrings)
unique_substrings.remove(substring)


# @lc code=end

0 comments on commit 408e83d

Please sign in to comment.