Home » Interview Questions » String Interview Questions » split-four-distinct-strings

split-four-distinct-strings


()

Check if the given input string can split into 4 strings such that each string is non-empty and different from each other.

Examples

a) Input string : “tutorials-cup”
Output : Yes
Here, split string into tut, oril, s-c, up

b) Input string: “aabab”
Output : No

Algorithm

1. If length of string is greater than or equal to 10, return true. Here, if length is equal to 10, strings with lengths 1, 2, 3, 4 can be formed which are distinct. So, return true.

2. Else run brute force technique to find four sub-strings that are different and can form given input string.

C++ Program

#include <bits/stdc++.h>

using namespace std;

bool CheckSplit(string str)
{
    //If size is greatar than 10 return true  
    if (str.size() >= 10)
    {
        return true;
    }
    //Brute Force technique
    for (int i =1; i < str.size(); i++)
    {
        for (int j = i + 1; j < str.size(); j++)
        {
            for (int k = j + 1; k < str.size(); k++)
            {
                string sub1 = str.substr(0, i);
                string sub2 = str.substr(i, j - i);
                string sub3 = str.substr(j, k - j);
                string sub4 = str.substr(k, str.size() - k);
                //Check if sub-strings are distinct or not.
                if (sub1 != sub2 && sub1 != sub3 && sub1 != sub4 && sub2 != sub3 && sub2 != sub4 && sub3 != sub4)
                {
                    return true;
                }
            }
        }
    } 
    return false;
}
 
//Main function
int main()
{
    string str = "aabab";
    if (CheckSplit(str))
    {
        cout<<"Yes"<<endl;
    }
    else
    {
        cout<<"No"<<endl;   
    }
    return 0;
}

Try It

 

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions