Split a String Into the Max Number of Unique Substrings

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.

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'].

思路:题目意思是求能够分开的string的个数最大值,比赛的时候,我理解错了,理解成种类了。题目要求的是个数; 

class Solution {
    public int maxUniqueSplit(String s) {
        int[] res = new int[]{0};
        HashSet<String> visited = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        dfs(s, 0, visited, sb, res);
        return res[0];
    }
    
    private void dfs(String s, int index, HashSet<String> visited, StringBuilder sb, int[] res) {
        if(index == s.length() && sb.toString().equals(s)) {
            res[0] = Math.max(res[0], visited.size());
            return;
        }
        for(int i = index; i < s.length(); i++) {
            String substr = s.substring(index, i + 1);
            if(!visited.contains(substr) && !substr.equals("")) {
                visited.add(substr);
                sb.append(substr);
                dfs(s, i + 1, visited, sb, res);
                sb.setLength(sb.length() - substr.length());
                visited.remove(substr);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值