1

Example

suppose string given is 'abccbaad'

Then, sub-string will be 'abc' and its reverse will be 'cba'

both exist in the given string.

how will you find both of them ?

please provide code snippets if possible.

Note: length of substring > 1

update: characters used in a substring from a position should not be used again in reversed string.

For eg. suppose 'c' from index 2 is used in substring then, it again should not be used in reversed string but 'c' from index 3 is allowed.

YaSh Chaudhary
  • 2,605
  • 8
  • 37
  • 74

1 Answers1

1

I am assuming that you want to find all substrings whose reverse is also present in the given string.

In that case, building on top of this answer - find all substrings :

def get_all_substrings(input_string):
    output_strings = list()
    length = len(input_string)
    for i in xrange(length): # Iterate through all indices of the string
        for j in xrange(i + 1, length):  # Iterate through indices starting from i + 1 to end of the string, so as to obtain substrings of length > 1
            substr = input_string[i:j + 1] # Slice the substring
            if substr[::-1] in input_string: # Check if the substring's reverse exists in the original string
                output_strings.append(substr) # If it does, add it to a list
    return output_strings
print get_all_substrings("abccbaad") # Output - ['ab', 'abc', 'abcc', 'abccb', 'abccba', 'bc', 'bcc', 'bccb', 'bccba', 'cc', 'ccb', 'ccba', 'cb', 'cba', 'ba', 'aa']
Ganesh Tata
  • 1,118
  • 8
  • 26
  • Sry maybe I didn't clear my question but I have updated now ! Ty :) – YaSh Chaudhary Nov 12 '17 at 06:36
  • @YaShChaudhary Please give a concrete example of the expected input and output, since I am unable to figure out the exact requirement of the question. A sample input string, and a sample output followed by an explanation of the reasoning behind the output should do. – Ganesh Tata Nov 12 '17 at 06:51