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'].
思路:题目意思是求能够分开的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);
}
}
}
}