Advertisement
aqibm

Untitled

Apr 8th, 2025
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <unordered_set>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. class Solution {
  9. public:
  10. // Main function: returns the maximum unique split as a vector of strings.
  11. vector<string> maxUniqueSplit(string s) {
  12. unordered_set<string> seen;
  13. auto res = backtrack(s, 0, seen);
  14. return res.second;
  15. }
  16.  
  17. private:
  18. // Returns a pair {maxCount, splitVector} for substring s[start:].
  19. // maxCount = maximum number of unique substrings obtainable
  20. // splitVector = corresponding splitting (in order) that achieves that count.
  21. pair<int, vector<string>> backtrack(const string &s, int start, unordered_set<string> &seen) {
  22. int n = s.size();
  23. if (start == n) {
  24. // Reached the end: return count 0 and an empty splitting.
  25. return {0, vector<string>()};
  26. }
  27.  
  28. int maxCount = 0;
  29. vector<string> bestSplitting; // best splitting for this subproblem
  30.  
  31. // Try every possible substring starting from index 'start'
  32. for (int end = start + 1; end <= n; ++end) {
  33. string substring = s.substr(start, end - start);
  34. // If this substring hasn't been used yet
  35. if (seen.find(substring) == seen.end()) {
  36. // Mark it as used
  37. seen.insert(substring);
  38. // Recurse from 'end'
  39. auto candidate = backtrack(s, end, seen);
  40. int currCount = 1 + candidate.first;
  41. // Check if this candidate produces a larger count.
  42. if (currCount > maxCount) {
  43. maxCount = currCount;
  44. bestSplitting = candidate.second;
  45. // Prepend the current substring.
  46. bestSplitting.insert(bestSplitting.begin(), substring);
  47. }
  48. // Backtrack: remove the substring from seen
  49. seen.erase(substring);
  50. }
  51. }
  52. return {maxCount, bestSplitting};
  53. }
  54. };
  55.  
  56. int main() {
  57. Solution sol;
  58.  
  59. // Example 1:
  60. string s1 = "goooooogle";
  61. // Expected (one possible answer): ["g", "o", "oo", "ooo", "gl", "e"]
  62. vector<string> split1 = sol.maxUniqueSplit(s1);
  63. cout << "Splitting for \"" << s1 << "\": ";
  64. for (auto &part : split1) {
  65. cout << "\"" << part << "\" ";
  66. }
  67. cout << "\n";
  68.  
  69. // Example 2:
  70. string s2 = "abccccd";
  71. // Expected (one possible answer): ["a", "b", "c", "cc", "cd"]
  72. vector<string> split2 = sol.maxUniqueSplit(s2);
  73. cout << "Splitting for \"" << s2 << "\": ";
  74. for (auto &part : split2) {
  75. cout << "\"" << part << "\" ";
  76. }
  77. cout << "\n";
  78.  
  79. return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement