- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- for k in range j + 1 to size of s - 1, do
- for j in range i + 1 to size of s - 1, do
- return False
Example
Let us see the following implementation to get better understanding −
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
Advertisements