Skip to content

1593. Split a String Into the Max Number of Unique Substrings 👍

  • Time: $O(2^n)$
  • Space: $O(2^n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int maxUniqueSplit(string s) {
    size_t ans = 0;
    dfs(s, 0, {}, ans);
    return ans;
  }

 private:
  void dfs(const string& s, int start, unordered_set<string>&& seen,
           size_t& ans) {
    if (start == s.length()) {
      ans = max(ans, seen.size());
      return;
    }

    for (int i = 1; start + i <= s.length(); ++i) {
      const string cand = s.substr(start, i);
      if (seen.contains(cand))
        continue;
      seen.insert(cand);
      dfs(s, start + i, std::move(seen), ans);
      seen.erase(cand);
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int maxUniqueSplit(String s) {
    dfs(s, 0, new HashSet<>());
    return ans;
  }

  private int ans = 0;

  private void dfs(final String s, int start, Set<String> seen) {
    if (start == s.length()) {
      ans = Math.max(ans, seen.size());
      return;
    }

    for (int i = start + 1; i <= s.length(); ++i) {
      final String cand = s.substring(start, i);
      if (seen.contains(cand))
        continue;
      seen.add(cand);
      dfs(s, i, seen);
      seen.remove(cand);
    }
  }
}