鱼C论坛

 找回密码
 立即注册
查看: 2658|回复: 0

[学习笔记] Leetcode 1593. Split a String Into the Max Number of Unique Substrings

[复制链接]
发表于 2020-9-21 08:06:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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.
class Solution:
    def maxUniqueSplit(self, s: str) -> int:
        def backtrack(s, hashset):
            max_val = 0
            
            for i in range(1, len(s) + 1):
                curt = s[:i]
                
                if curt not in hashset:
                    hashset.add(curt)
                    max_val = max(max_val, 1 + backtrack(s[i:], hashset))
                    hashset.discard(curt)
            
            return max_val
        
        return backtrack(s, set())

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 07:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表