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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int helper(string& s, int p, unordered_set<string>& us) {
if(s.length() == p) return us.size();
int res = 0;
string cut = "";
for(int i = p; i < s.length(); i++) {
cut.push_back(s[i]);
if(!us.count(cut)) {
us.insert(cut);
res = max(res, helper(s, i + 1, us));
us.erase(cut);
}
}
return res;
}
public:
int maxUniqueSplit(string s) {
return helper(s, 0, unordered_set<string>() = {});
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/01/PS/LeetCode/split-a-string-into-the-max-number-of-unique-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.