Check if given string can be split into four distinct strings in Python


Suppose we have a string s, we have to check whether we can split it into four sub-strings such that each of them are non-empty and unique.

So, if the input is like s = "helloworld", then the output will be True as one of the possible set of sub-strings are ["hel", "lo", "wor", "ld"]

To solve this, we will follow these steps −

  • if size of s >= 10, then
    • return True
  • for i in range 1 to size of s - 1, do
    • for j in range i + 1 to size of s - 1, do
      • for k in range j + 1 to size of s - 1, do
        • sub1 := s[from index 0 to i - 1]
        • sub2 := s[from index i to j - i - 1]
        • sub3 := s[from index j to k - j - 1]
        • sub4 := s[from index k to size of s - k - 1]
        • if sub1 sub2 sub3 and sub4 all are distinct, then
          • return True
  • return False

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s):
   if len(s) >= 10:
      return True
   for i in range(1, len(s)):
      for j in range(i + 1, len(s)):
         for k in range(j + 1, len(s)):
            sub1 = s[0:i]
            sub2 = s[i:j - i]
            sub3 = s[j: k - j]
            sub4 = s[k: len(s) - k]
            if sub1 != sub2 and sub1 != sub3 and sub1 != sub4 and sub2 != sub3 and sub2 != sub4 and sub3 != sub4:
               return True
   return False
s = "helloworld"
print (solve(s))

Input

"helloworld"

Output

True

Updated on: 18-Jan-2021

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements