[LeetCode] 1593. 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.

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.

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-a-string-into-the-max-number-of-unique-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是backtracking。我们需要一个hashset来判断是否存在重复的子串,回溯函数的base case是指针遍历到 input 字符串尾部,就结算 hashset 里面子串的个数。回溯函数往下遍历的过程中,index 指针是当前子串的起点,i 指针找的是当前子串的终点,当新生成的子串不存在于hashset的时候,我们就把他加入hashset并以当前子串的终点 i 作为下个子串的起点进行下一步递归调用。

时间O(16!) - 因为input字符串最长只有16个字母

空间O(n)

Java实现

 1 class Solution {
 2     int res = 0;
 3 
 4     public int maxUniqueSplit(String s) {
 5         HashSet<String> set = new HashSet<>();
 6         helper(s, 0, set);
 7         return res;
 8     }
 9 
10     private void helper(String s, int index, HashSet<String> set) {
11         // base case
12         if (index == s.length()) {
13             res = Math.max(res, set.size());
14         }
15         for (int i = index + 1; i <= s.length(); i++) {
16             String str = s.substring(index, i);
17             if (!set.contains(str)) {
18                 set.add(str);
19                 helper(s, i, set);
20                 set.remove(str);
21             }
22         }
23     }
24 }

 

LeetCode 题目总结

上一篇:SSLOJ 1316.血色先锋军


下一篇:1316 你能知道这是几进制数?