Skip to content

LeetCode 5520 拆分字符串使唯一子字符串的数目最大#

目录#

1. 题目描述#

1.1. Limit#

Time Limit: 2000 ms

Memory Limit: 131072 kB

1.2. Problem Description#

给你一个字符串 s ,请你拆分该字符串,并返回拆分后唯一子字符串的最大数目。

字符串 s 拆分后可以得到若干 非空子字符串 ,这些子字符串连接后应当能够还原为原字符串。但是拆分出来的每个子字符串都必须是 唯一的

注意:子字符串 是字符串中的一个连续字符序列。

1.3. Sample Input 1#

输入:s = "ababccc"

1.4. Sample Output 1#

输出:5
解释:一种最大拆分方法为 ['a', 'b', 'ab', 'c', 'cc'] 。像 ['a', 'b', 'a', 'b', 'c', 'cc'] 这样拆分不满足题目要求,因为其中的 'a' 和 'b' 都出现了不止一次。

1.5. Sample Input 2#

输入:s = "aba"

1.6. Sample Output 2#

输出:2
解释:一种最大拆分方法为 ['a', 'ba'] 。

1.7. Source#

LeetCode 5520 拆分字符串使唯一子字符串的数目最大

2. 解读#

DFS遍历所有长度。


3. 代码#

class Solution {
public:
    unordered_set<string> st;
    int ans = 0;

    int DFS(string& str, size_t pos)
    {
        // 停止搜索
        if (pos >= str.size()) {
            return st.size();
        }
        // 遍历所有长度
        for (size_t i = 1; i <= str.size() - pos; i++) {
            // 若未在集合中存储
            if (st.find(str.substr(pos, i)) == st.end()) {
                // 插入集合
                st.insert(str.substr(pos, i));
                // 搜索下一字符
                ans = max(ans, DFS(str, pos + i));
                // 将字符串从集合中删除,退回上一状态
                st.erase(str.substr(pos, i));
            }
        }
        return ans;
    }

    int maxUniqueSplit(string s)
    {
        return DFS(s, 0);
    }
};

联系邮箱:curren_wong@163.com

CSDN:https://me.csdn.net/qq_41729780

知乎:https://zhuanlan.zhihu.com/c_1225417532351741952

公众号:复杂网络与机器学习

欢迎关注/转载,有问题欢迎通过邮箱交流。

二维码

Back to top