How to check if a string can split into 4 distinct substrings in C++

2 Answers

0 votes
#include <unordered_set>
#include <iostream>
#include <string>
 
bool canSplitInto4DistinctSubstrings(const std::string str) {
    int size = str.length();
 
    if (size < 4)
        return false;
 
    for (int i = 1; i < size - 2; i++) {
        for (int j = i + 1; j < size - 1; j++) {
            for (int k = j + 1; k < size; k++) {
                std::string part1 = str.substr(0, i);
                std::string part2 = str.substr(i, j - i);
                std::string part3 = str.substr(j, k - j);
                std::string part4 = str.substr(k, size - k);
 
                if (!part1.empty() && !part2.empty() && !part3.empty() && !part4.empty()) {
                    std::unordered_set<std::string> unique_parts = {part1, part2, part3, part4};
                    if (unique_parts.size() == 4) {
                        std::cout << part1 << " " << part2 << " " << part3 << " " << part4 << "\n";
                        return true;
                    }
                }
            }
        }
    }
 
    return false;
}
 
int main() {
    std::string str = "AlbusDumbledore";
 
    if (canSplitInto4DistinctSubstrings(str)) {
        std::cout << "yes";
    } else {
        std::cout << "no";
    }
}
 
 
 
 
/*
run:
 
A l b usDumbledore
yes
 
*/

 



answered Jul 25, 2023 by avibootz
edited Feb 14, 2024 by avibootz
0 votes
#include <unordered_set>
#include <iostream>
#include <string>
 
bool canSplitInto4DistinctSubstrings(const std::string str) {
    int size = str.length();
 
    if (size < 4)
        return false;
 
    for (int i = 2; i < size - 2; i++) {
        for (int j = i + 2; j < size - 1; j++) {
            for (int k = j + 2; k < size; k++) {
                std::string part1 = str.substr(0, i);
                std::string part2 = str.substr(i, j - i);
                std::string part3 = str.substr(j, k - j);
                std::string part4 = str.substr(k, size - k);
 
                if (!part1.empty() && !part2.empty() && !part3.empty() && !part4.empty()) {
                    std::unordered_set<std::string> unique_parts = {part1, part2, part3, part4};
                    if (unique_parts.size() == 4) {
                        std::cout << part1 << " " << part2 << " " << part3 << " " << part4 << "\n";
                        return true;
                    }
                }
            }
        }
    }
 
    return false;
}
 
int main() {
    std::string str = "AlbusDumbledore";
 
    if (canSplitInto4DistinctSubstrings(str)) {
        std::cout << "yes";
    } else {
        std::cout << "no";
    }
}
 
 
 
 
/*
run:
 
Al bu sD umbledore
yes
 
*/

 



answered Jul 25, 2023 by avibootz
edited Feb 14, 2024 by avibootz

Related questions

...