I recently saw this problem and am really stuck at implementing it.
The problem is to generate all possible alphabetically ordered substrings from given string.
Smaller Example : For string xcv
I am required to generate the output :
c cv cvx v vx x
Bigger Example : For the string hgrte
I am required to generate the following substrings :
e
eg
egh
eghr
eghrt
eght
egr
egrt
egt
eh
ehr
ehrt
eht
er
ert
et
g
gh
ghr
ghrt
ght
gr
grt
gt
h
hr
hrt
ht
r
rt
t
This is my implementation which didn't produce the desired output.
s = sorted(list(input()))
s = ''.join(s)
for i in range(len(s)):
for j in range(i+1, len(s)+1):
temp = s[i:j]
print(''.join(temp))
This is the output of my code :
e
eg
egh
eghr
eghrt
g
gh
ghr
ghrt
h
hr
hrt
r
rt
t
[]
I know I have to use backtracking and recursion after printing eghrt
, but I am really stuck at implementing it.
Thanks in advance :)