Longest Substring

Given a string, find the substring based on following conditions:

  • The substring must be the longest one of all the possible substring in the given string.
  • There must not be any repeating characters in the substring.
  • If there is more than one substring satisfying the above two conditions, then print the substring which occurs first.
  • Length of the substring must be minimum 3.

If there is no substring satisfying all the aforementioned conditions then print -1.

Source Code:
str1=input()
substr=""
maxChars=0
for i in range(len(str1)-1):
    k=i
    for j in range(i+1,len(str1)):
        if str1[j] not in str1[i:j]:
            k+=1
        else:
            break
    if len(str1[i:k+1])>=maxChars:
        maxChars=len(str1[i:k+1])
        substr=str1[i:k+1]
if maxChars>=3:
    print(substr)
else:
    print("-1")

Sample Input1:
hello
Sample Output1:
hel
Sample Input2:
heello
Sample Output2:
-1

No comments:

Post a Comment

Total Pageviews