ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 1593. Split a String Into the Max Number of Unique Substrings

2021-01-07 02:02:36  阅读:239  来源: 互联网

标签:子串 String Max Into substrings split 拆分 字符串 string


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 题目总结

标签:子串,String,Max,Into,substrings,split,拆分,字符串,string
来源: https://www.cnblogs.com/cnoodle/p/14244326.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有